Working a Vec in Rust
The Vec methods that do real work: filtering in place, sorting by key, windows.
fn main() {
let mut words = vec!["pear", "fig", "apple", "kiwi", "plum"];
words.retain(|w| w.len() > 3);
words.sort_by_key(|w| w.len());
println!("{:?}", words);
let nums = [1, 3, 6, 10, 15];
for pair in nums.windows(2) {
print!("{} ", pair[1] - pair[0]);
}
println!();
for chunk in nums.chunks(2) {
print!("{:?}", chunk);
}
println!();
}
How it works
retainkeeps the elements whose test passes.sort_by_keysorts by a derived value.windowsandchunksview a slice in overlapping or fixed groups.
Keywords and builtins used here
fnforinletmainmut
The run, in numbers
- Lines
- 18
- Characters to type
- 341
- Tokens
- 143
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 95 seconds.
Step 2 of 8 in Collections, step 31 of 39 in Language basics.