Skip to content

Commit 21b24e1

Browse files
committed
Add get_opt to std::vec
1 parent 9883a62 commit 21b24e1

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)