In Rust, can you own a string literal?

佐手、 提交于 2019-12-17 21:00:12

问题


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:


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.



来源:https://stackoverflow.com/questions/57225055/in-rust-can-you-own-a-string-literal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!