Slices in Rust
Borrowing a contiguous part of a string or array.
fn first_word(s: &str) -> &str {
match s.find(' ') {
Some(i) => &s[..i],
None => s,
}
}
fn main() {
let phrase = String::from("touch typing code");
let word = first_word(&phrase);
let nums = [1, 2, 3, 4, 5];
let middle = &nums[1..4];
println!("{word} {}", middle.len());
}
How it works
&s[..i]slices a string without copying.- Returning a
&strborrows from the input. &nums[1..4]slices an array the same way.
Keywords and builtins used here
NoneSomeStringfirst_wordfnletmainmatchstr
The run, in numbers
- Lines
- 14
- Characters to type
- 273
- Tokens
- 106
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 67 seconds.
Step 1 of 4 in Slices & strings, step 7 of 15 in Ownership & borrowing.