mel*_*low 9 string reference string-literals ownership rust
根据The Rust 的书:
Rust 中的每个值都有一个变量,称为其所有者。一次只能有一个所有者。当所有者超出范围时,该值将被删除。
静态项目不会在程序结束时调用 drop。
在阅读了这篇 SO post并给出了下面的代码后,我明白这foo是一个值,其变量y相当于&y因为“字符串文字是字符串切片”,被称为它的owner. 那是对的吗?还是静态项目没有所有者?
let x = String::from("foo"); // heap allocated, mutable, owned
let y = "foo" // statically allocated to rust executable, immutable
Run Code Online (Sandbox Code Playgroud)
我想知道,因为与拥有的不同String,字符串文字没有移动,大概是因为它们存储在.rodata可执行文件中。
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")
}
Run Code Online (Sandbox Code Playgroud)
更新:根据The Rust 书:
这些 & 符号是引用,它们允许您引用某个值而不拥有它的所有权……另一种没有所有权的数据类型是切片。
由于字符串文字是字符串切片 ( &str) (请参阅上面的引文),因此从逻辑上讲,它们没有所有权。理由似乎是编译器需要一个已知大小的数据结构:一个引用:
let s1: str = "foo"; // [rustc E0277] the size for values of type `str` cannot be known at compilation time [E]
Run Code Online (Sandbox Code Playgroud)
字符串切片引用 ( &str) 不拥有它指向的字符串切片,而是借用了它。您可以有多个对一个对象的不可变引用,这就是为什么您的第二个代码示例是正确的并且借用检查器很乐意接受它。
我想你可以说具有'static生命周期的类型没有所有者,或者main函数之外的东西拥有它。所有者仅在拥有对象的生命周期结束时才重要(如果您拥有它,则需要释放资源)。对于引用,只有生命周期很重要。