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`?)
This commit is contained in:
bors 2013-10-12 20:16:19 -07:00
commit 0bad7e1a37

View File

@ -840,6 +840,7 @@ pub trait ImmutableVector<'self, T> {
fn window_iter(self, size: uint) -> WindowIter<'self, T>;
fn chunk_iter(self, size: uint) -> ChunkIter<'self, T>;
fn get_opt(&self, index: uint) -> Option<&'self T>;
fn head(&self) -> &'self T;
fn head_opt(&self) -> Option<&'self T>;
fn tail(&self) -> &'self [T];
@ -1019,6 +1020,13 @@ impl<'self,T> ImmutableVector<'self, T> for &'self [T] {
ChunkIter { v: self, size: size }
}
/// Returns the element of a vector at the given index, or `None` if the
/// index is out of bounds
#[inline]
fn get_opt(&self, index: uint) -> Option<&'self T> {
if index < self.len() { Some(&self[index]) } else { None }
}
/// Returns the first element of a vector, failing if the vector is empty.
#[inline]
fn head(&self) -> &'self T {
@ -2574,6 +2582,16 @@ mod tests {
assert_eq!(v2.len(), 2);
}
#[test]
fn test_get_opt() {
let mut a = ~[11];
assert_eq!(a.get_opt(1), None);
a = ~[11, 12];
assert_eq!(a.get_opt(1).unwrap(), &12);
a = ~[11, 12, 13];
assert_eq!(a.get_opt(1).unwrap(), &12);
}
#[test]
fn test_head() {
let mut a = ~[11];