As per rust doc, string slice is:
This string is statically allocated, meaning that it's saved inside our compiled program, and exists for the entire duration it runs.
What about vector slices? Are these bytecode hardcoded values?
Rust doc does not explain properly what vector slice is:
Similar to &str, a slice is a reference to another array. We can get a slice from a vector by using the as_slice() method:
let vec = vec![1i, 2i, 3i];
let slice = vec.as_slice();
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:
T
) in an array of type T
sIf 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With