35 lines
1.2 KiB
Markdown
35 lines
1.2 KiB
Markdown
---
|
|
name = "Vecs and slices"
|
|
difficulty = 2
|
|
exercises = ["access.md"]
|
|
---
|
|
|
|
Let's now look at some functions on [`slice`](https://doc.rust-lang.org/std/primitive.slice.html)s and [`Vec`](https://doc.rust-lang.org/std/vec/struct.Vec.html)s. Instead of manualy checking things we will follow the type system using `Option`s and `Result`s we saw earlier.
|
|
|
|
```note
|
|
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).
|
|
```
|
|
|
|
```deepening
|
|
`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>`.
|
|
```
|
|
|
|
```prototype
|
|
/// 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!()
|
|
}
|
|
```
|
|
|
|
```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));
|
|
}
|
|
```
|
|
|