13

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]

1 Answer 1

9

A string slice reference (&str) does not own the string slice that it points to, it borrows it. You can have several immutable references to an object, that's why your second code sample is correct and the borrow checker is happy to accept it.

I think you can say that types with the 'static lifetime have no owner, or that something outside of the main function owns it. The owner only matters when the lifetime of the owning object ends (if you own it, you need to free resources). For references only lifetimes matter.

1
  • 6
    One could add: &str is a type in itself. This type implement Copy which means that it does not follow move semantics, but copy semantics (@mellow-yellow you will read about that trait in the book as well). And you can also say that y is indeed the owner, but not of the actual string (as this is in the .rodata section), but of the reference to it. y is the owner of the reference (pointer) of type &str. I hope these additions make some sense. Jul 26, 2019 at 21:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.