Slices (&str / &[T])
A slice is a reference to a portion of a collection and does not have ownership. There are two types: string slices (&str) and array slices (&[T]).
Syntax
// String slice let s: &str = "hello"; // A string literal is of type &str. let slice = &string[start..end]; // Gets a partial slice from a String. // Array slice let slice: &[i32] = &array[start..end]; let full: &[i32] = &array[..]; // A slice of the entire array.
Slice Notation
| Notation | Description |
|---|---|
| &s[0..5] | A slice from index 0 up to (but not including) index 5. |
| &s[..5] | A slice from the beginning up to index 4 (start omitted). |
| &s[3..] | A slice from index 3 to the end (end omitted). |
| &s[..] | A slice of the entire collection. |
| &str | The string slice type. This is also the type of string literals. |
| &[T] | An array slice type for elements of type T. |
Sample Code
fn first_word(s: &str) -> &str {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &s[0..i]; // Returns the portion before the first space.
}
}
&s[..] // Returns the whole string if no space is found.
}
fn sum_slice(nums: &[i32]) -> i32 {
nums.iter().sum()
}
fn main() {
// String slice
let s = String::from("hello world");
let hello = &s[0..5];
let world = &s[6..11];
println!("{} {}", hello, world); // Prints "hello world".
let word = first_word(&s);
println!("First word: {}", word); // Prints "hello".
// Array slice
let a = [1, 2, 3, 4, 5];
let slice = &a[1..4];
println!("{:?}", slice); // Prints "[2, 3, 4]".
println!("Sum: {}", sum_slice(&a)); // Prints "15".
}
Notes
Because a slice is a reference to the original data, no copying occurs. Using &str instead of String as a function parameter makes the function more flexible, since it accepts both string literals and String values.
Slicing a string that contains multi-byte characters (such as Japanese) at a non-character boundary will cause a runtime panic. To work with individual characters, use the chars() method (see String::chars()).
The lifetime of a slice is tied to its source data — once the source is freed, the slice becomes invalid. For more details, see Lifetimes ('a).
If you find any errors or copyright issues, please contact us.