Actually... it is not always statically allocated. Note the specific wording:
let string = "Hello there.";
This string is statically allocated, meaning that it's saved inside our compiled program, and exists for the entire duration it runs (empahsis mine).
In the case of a string literal, the string is statically allocated, and the string slice refers to it. However there are other cases of string slices where they refer to dynamically allocated strings.
In general, a slice is a contiguous sequence of elements in an array (wherever that array lives). Therefore, in Rust:
- a string slice is a slice of bytes in a UTF-8 encoded array
- a vector slice is a slice of elements (of type
T
) in an array of type T
s
If the array has a static lifetime (ie, exists for the whole duration of the program), then this is represented with the static
keyword:
&'static str
is a &str
(string slice) with such a lifetime, it is thus the precise types of string literals in Rust.
Otherwise, the lifetime is generally bounded to that of the array owner, for example:
let vec = vec!(1i, 2, 3); // create a dynamically allocated array of 3 `int`
let slice = vec.as_slice(); // create a slice into this array,
// the lifetime of which cannot (obviously)
// exceed that of the array.
thus if vec
has a lifetime 'a
, then slice
has for type &'a [int]
as can be seen in the type signature:
fn as_slice(&'a self) -> &'a [T]
(from the std::vec::Vec
page)