67 lines
2.0 KiB
Markdown
67 lines
2.0 KiB
Markdown
---
|
|
name = "Accessing values"
|
|
file = "src/vec/access.rs"
|
|
---
|
|
|
|
Instead of using the good old C-style bound checking:
|
|
|
|
```rust
|
|
if vec.len() < 1 {
|
|
return None;
|
|
} else {
|
|
// compiler still thinks this line can panic
|
|
return vec[0];
|
|
}
|
|
```
|
|
|
|
Try to implement these functions using non-panicking methods like [`last`](https://doc.rust-lang.org/std/primitive.slice.html#method.last), [`last_chunk`](https://doc.rust-lang.org/std/primitive.slice.html#method.last_chunk), or [`get`](https://doc.rust-lang.org/std/primitive.slice.html#method.get).
|
|
|
|
> ## note
|
|
> Don't be afraid of the `get` function prototype, look at the examples, they are fairly simple, it's just that `get` can work on multiple types, allowing for slice indexing as well as single element indexing.
|
|
|
|
> ## note
|
|
> You may want to look at the [`sort`](https://doc.rust-lang.org/std/primitive.slice.html#method.sort) and [`to_vec`](https://doc.rust-lang.org/std/primitive.slice.html#method.to_vec) functions for the median.
|
|
|
|
```prototype
|
|
/// Add the last two numbers of the input slice.
|
|
///
|
|
/// # Return value
|
|
/// `None` if the slice is not large enough
|
|
/// `Some(result)` if the slice has at least 2 elements
|
|
pub fn add_last_two(v: &[f32]) -> Option<f32> {
|
|
unimplemented!()
|
|
}
|
|
|
|
/// Duplicate the top element from the stack if it exist
|
|
/// (the stack is represented as a Vec with top == last)
|
|
///
|
|
/// # Return value
|
|
/// `Some(())` if the operation succeeded
|
|
/// `None` if not
|
|
pub fn dup_top(v: &mut Vec<f32>) -> Option<()> {
|
|
unimplemented!()
|
|
}
|
|
|
|
/// Compute the median of a slice in place (if the slice was sorted, it would be the middle element)
|
|
pub fn median(v: &[i32]) -> Option<i32> {
|
|
unimplemented!()
|
|
}
|
|
```
|
|
|
|
```example
|
|
fn main() {
|
|
assert_eq!(add_last_two(&[]), None);
|
|
assert_eq!(add_last_two(&[10.0]), None);
|
|
assert_eq!(add_last_two(&[1.0, 2.0, 3.0]), Some(5.0));
|
|
|
|
let mut stack = vec![1.0];
|
|
assert!(dup_top(&mut stack).is_some());
|
|
assert_eq!(&stack, &[1.0, 1.0]);
|
|
|
|
stack.clear();
|
|
assert!(dup_top(&mut stack).is_none());
|
|
|
|
assert_eq!(median(&[2, 1, 3]), Some(2));
|
|
}
|
|
```
|