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
fn main() {
let text = "rustacean";
let take = ;
let part = &text[..take];
println!("{part}");
}
fn main() {
let text = "rustacean";
let take = ;
let part = &text[..take];
println!("{part}");
}
fn main() {
let text = "rustacean";
let take = ;
let part = &text[..take];
println!("{part}");
}
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.