Rust Slices and Tuples
A slice is a view of part of a collection, written &v[1..3]. It borrows rather than copies. Tuples group values of different types.
ExampleRust
fn first_word(s: &str) -> &str {
s.split(' ').next().unwrap_or("")
}
fn min_max(v: &[i32]) -> (i32, i32) {
(*v.iter().min().unwrap(), *v.iter().max().unwrap())
}
fn main() {
let numbers = [10, 20, 30, 40, 50];
let middle = &numbers[1..4];
println!("{:?} {}", middle, middle.len());
println!("{}", first_word("hello brave world"));
let (lo, hi) = min_max(&numbers);
println!("{} {}", lo, hi);
let person = ("Ada", 36, true);
println!("{} is {} ({})", person.0, person.1, person.2);
}Output
[20, 30, 40] 3 hello 10 50 Ada is 36 (true)
Quick check
What is a slice?
Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.
Tip: use the left and right arrow keys to move between lessons.