Skip to content

Commit 0bad7e1

Browse files
committed
auto merge of #9608 : hmarr/rust/vec-get-opt, r=huonw
This adds `get_opt` to `std::vec`, which looks up an item by index and returns an `Option`. If the given index is out of range, `None` will be returned, otherwise a `Some`-wrapped item will be returned. Example use case: ```rust use std::os; fn say_hello(name: &str) { println(fmt!("Hello, %s", name)); } fn main(){ // Try to get the first cmd line arg, but default to "World" let args = os::args(); let default = ~"World"; say_hello(*args.get_opt(1).unwrap_or(&default)); } ``` If there's an existing way of implementing this pattern that's cleaner, I'll happily close this. I'm also open to naming suggestions (`index_opt`?)
2 parents c6e3501 + 21b24e1 commit 0bad7e1

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

src/libstd/vec.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -840,6 +840,7 @@ pub trait ImmutableVector<'self, T> {
840840
fn window_iter(self, size: uint) -> WindowIter<'self, T>;
841841
fn chunk_iter(self, size: uint) -> ChunkIter<'self, T>;
842842

843+
fn get_opt(&self, index: uint) -> Option<&'self T>;
843844
fn head(&self) -> &'self T;
844845
fn head_opt(&self) -> Option<&'self T>;
845846
fn tail(&self) -> &'self [T];
@@ -1019,6 +1020,13 @@ impl<'self,T> ImmutableVector<'self, T> for &'self [T] {
10191020
ChunkIter { v: self, size: size }
10201021
}
10211022

1023+
/// Returns the element of a vector at the given index, or `None` if the
1024+
/// index is out of bounds
1025+
#[inline]
1026+
fn get_opt(&self, index: uint) -> Option<&'self T> {
1027+
if index < self.len() { Some(&self[index]) } else { None }
1028+
}
1029+
10221030
/// Returns the first element of a vector, failing if the vector is empty.
10231031
#[inline]
10241032
fn head(&self) -> &'self T {
@@ -2574,6 +2582,16 @@ mod tests {
25742582
assert_eq!(v2.len(), 2);
25752583
}
25762584

2585+
#[test]
2586+
fn test_get_opt() {
2587+
let mut a = ~[11];
2588+
assert_eq!(a.get_opt(1), None);
2589+
a = ~[11, 12];
2590+
assert_eq!(a.get_opt(1).unwrap(), &12);
2591+
a = ~[11, 12, 13];
2592+
assert_eq!(a.get_opt(1).unwrap(), &12);
2593+
}
2594+
25772595
#[test]
25782596
fn test_head() {
25792597
let mut a = ~[11];

0 commit comments

Comments
 (0)