Lifetimes and References
String Slice
Borrowing Part of Text
A string slice borrows a range of bytes from existing text. The borrowed slice cannot outlive the original string.
Program
Play the program to choose how much of a word is borrowed as a slice.
string_slice.rs
Replay: real traced execution (multi-file project)
fn main() {
let text = "rustacean";
let take = 4;
let part = &text[..take];
println!("{part}");
}
fn main() {
let text = "rustacean";
let take = 5;
let part = &text[..take];
println!("{part}");
}
fn main() {
let text = "rustacean";
let take = 9;
let part = &text[..take];
println!("{part}");
}
text ← "rustacean", take ← 4, part ← "rust"
1fn main() {2 let tex→ "rustacean"t = "rustacean";3 let tak→ 4e = 4; //@take=5, 94 let par→ "rust"t = &text[..take"rust"];5 println!("{part}");6}outputrust
text ← "rustacean", take ← 5, part ← "rusta"
1fn main() {2 let tex→ "rustacean"t = "rustacean";3 let tak→ 5e = 5;4 let par→ "rusta"t = &text[..take"rusta"];5 println!("{part}");6}outputrusta
text ← "rustacean", take ← 9, part ← "rustacean"
1fn main() {2 let tex→ "rustacean"t = "rustacean";3 let tak→ 9e = 9;4 let par→ "rustacean"t = &text[..take"rustacean"];5 println!("{part}");6}outputrustacean
string slice
`&text[..take]` borrows part of the string data.
borrowed view
The slice points into `text`; it does not allocate a new string.
valid boundary
Slice indexes must land on UTF-8 character boundaries.