According to The Rust book:
Each value in Rust has a variable that’s called its owner. There can be only one owner at a time. When the owner goes out of scope, the value will be dropped.
According to rust-lang.org:
Static items do not call drop at the end of the program.
After reading this SO post, and given the code below, I understand that foo
is a value whose variable y
, equivalent to &y
since "string literals are string slices", is called its owner
. Is that correct? Or do static items have no owner?
let x = String::from("foo"); // heap allocated, mutable, owned
let y = "foo" // statically allocated to rust executable, immutable
I'm wondering because unlike an owned String
, string literals are not moved, presumably because they're stored in .rodata
in the executable.
fn main() {
let s1 = "foo"; // as opposed to String::from("foo")
let s2 = s1; // not moved
let s3 = s2; // no error, unlike String::from("foo")
}
UPDATE: According to The Rust book:
These ampersands are references, and they allow you to refer to some value without taking ownership of it...Another data type that does not have ownership is the slice.
Since string literals are string slices (&str
) (see citation above), they, logically, do not have ownership. The rationale seems to be that the compiler requires a data structure with a known size: a reference:
let s1: str = "foo"; // [rustc E0277] the size for values of type `str` cannot be known at compilation time [E]