Rust Slice Type - rFronteddu/general_wiki GitHub Wiki
Slices let you reference a contiguous sequence of elements in a collection rather than the whole collection. A slice is a kind of reference, so it is a non-owning pointer.
A string slice is a reference to part of a String, and it looks like this:
let s = String::from("hello world");
let hello: &str = &s[0..5];
let world: &str = &s[6..11];
let s2: &String = &s;
Rather than a reference to the entire String (like s2), hello is a reference to a portion of the String, specified in the extra [0..5] bit. We create slices using a range within brackets by specifying [starting_index..ending_index], where starting_index is the first position in the slice and ending_index is one more than the last position in the slice. Slices are special kinds of references because they are “fat” pointers, or pointers with metadata. Here, the metadata is the length of the slice.
Because slices are references, they also change the permissions on referenced data. For example, observe below that when hello is created as a slice of s, then s loses write and own permissions:
fn main() {
let mut s = String::from("hello"); // s +R +W +O
// requires R
let hello: &str = &s[0..5]; // s R -W -O
// hello +R - +O
// +hello +R - -
// Requires R
println!("{hello}"); // s R +W +O
// hello -R - -O
// +hello -R - -
// requires R and W
s.push_str(" world"); // s -R -W -O
}
With Rust’s .. range syntax, if you want to start at index zero, you can drop the value before the two periods. In other words, these are equal:
let s = String::from("hello");
let slice = &s[0..2];
let slice = &s[..2];
By the same token, if your slice includes the last byte of the String, you can drop the trailing number. You can also drop both values to take a slice of the entire string.
Note: String slice range indices must occur at valid UTF-8 character boundaries. If you attempt to create a string slice in the middle of a multibyte character, your program will exit with an error.
Example:
fn first_word(s: &String) -> &str {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &s[0..i];
}
}
&s[..]
}
The following would not compile:
fn main() {
let mut s = String::from("hello world");
let word = first_word(&s);
s.clear();
println!("the first word is: {}", word);
}
Recall from the borrowing rules that if we have an immutable reference to something, we cannot also take a mutable reference. Because clear needs to truncate the String, it needs to get a mutable reference. The println! after the call to clear uses the reference in word, so the immutable reference must still be active at that point. Rust disallows the mutable reference in clear and the immutable reference in word from existing at the same time, and compilation fails.
String literals are slices
Recall that we talked about string literals being stored inside the binary. Now that we know about slices, we can properly understand string literals:
let s = "Hello, world!";
The type of s here is &str: it’s a slice pointing to that specific point of the binary. This is also why string literals are immutable; &str is an immutable reference.
String slices as parameters
If we have a string slice, we can pass that directly. If we have a String, we can pass a slice of the String or a reference to the String. This flexibility takes advantage of deref coercions.
String slices, as you might imagine, are specific to strings. But there’s a more general slice type, too.
Remember: At runtime, a slice is represented as a “fat pointer” which contains a pointer to the beginning of the range and a length of the range. One advantage of slices over index-based ranges is that the slice cannot be invalidated while it’s being used.