1.2 KiB
1.2 KiB
name = "Vecs and slices" difficulty = 2 exercises = ["access.md"]
Let's now look at some functions on slices and Vecs. Instead of manualy checking things we will follow the type system using Options and Results we saw earlier.
Slices (`[T]`) represent some memory space containing an arbitrary number of elements of type `T`. Since they don't have a size known at compilation time, we can only access them through pointers, commonly `&[T]` (references to slices).
`Vec<T>` can be seen as [owned](https://doc.rust-lang.org/book/ch04-00-understanding-ownership.html) `[T]`, it means that every function working on a `&[T]` can work on a `&Vec<T>`.
/// Add the last two numbers of the input slice.
///
/// If the slice is not large enough, return `None`
/// If it is, return the computed value in a `Some`
pub fn add_last_two(v: &[f32]) -> Option<f32> {
unimplemented!()
}
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));
}