Slices
-
A slice is a dynamically sized view into a contiguous sequence of elements.
-
The type of a slice of elements of type
t
is[t]
(eg. a slice ofu32
is[u32]
). -
Slices can be created through bracket notation and a range rather than an index (eg.
array[5..6]
). -
Since slices do not have a known size at compile time, they cannot be assigned to local variables.
fn main() {
let array = [1, 2, 3, 4, 5];
// Err: the size for values of type `[i32]` cannot be known at compilation time
let slice: [i32] = array[1..2];
}
Slice References
-
Slices are usually seen in its borrowed form as a slice reference / shared slice / reference to a slice.
-
The type of a slice reference is
&[T]
. -
A slice reference is a fat pointer; in addition to being a regular reference, a slice reference contains the length of the slice it points to.
fn main() {
let array = [1, 2, 3, 4, 5];
let slice: &[i32] = &array[1..2];
}
-
A mutable slice reference,
&mut [T]
, allows mutating the elements the slice reference points to.
String Slices
-
The primitive string type is the string slice
str
, and is a slice of bytes (u8
) in the UTF-8 encoding. -
String slices are also commonly used in its borrowed form,
&str
. -
String literals are string slices.
fn main() {
// Owned String
let str_owned: String = String::from("Hello world!");
let str_owned_ref: &str = &str_owned;
// String literal
let str_literal: &str = "Hello world!";
}