在 Rust 中,你可以拥有一个字符串文字吗?
In Rust, can you own a string literal?
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.
Static items do not call drop at the end of the program.
读后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",称其owner
。那是对的吗?或者静态项目没有所有者?
let x = String::from("foo"); // heap allocated, mutable, owned
let y = "foo" // statically allocated to rust executable, immutable
我想知道,因为与拥有的 String
不同,字符串文字不会被移动,大概是因为它们是 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")
}
更新:根据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.
由于字符串文字是字符串切片 (&str
)(参见上面的引用),因此从逻辑上讲,它们没有所有权。理由似乎是编译器需要一个已知大小的数据结构:参考:
let s1: str = "foo"; // [rustc E0277] the size for values of type `str` cannot be known at compilation time [E]
字符串切片引用 (&str
) 不拥有它指向的字符串切片,而是借用它。您可以对一个对象有多个不可变引用,这就是为什么您的第二个代码示例是正确的并且借用检查器很乐意接受它的原因。
我想你可以说具有 'static
生命周期的类型没有所有者,或者 main
函数之外的东西拥有它。所有者仅在拥有对象的生命周期结束时才重要(如果拥有它,则需要释放资源)。仅供参考,生命周期很重要。
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.
Static items do not call drop at the end of the program.
读后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",称其owner
。那是对的吗?或者静态项目没有所有者?
let x = String::from("foo"); // heap allocated, mutable, owned
let y = "foo" // statically allocated to rust executable, immutable
我想知道,因为与拥有的 String
不同,字符串文字不会被移动,大概是因为它们是 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")
}
更新:根据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.
由于字符串文字是字符串切片 (&str
)(参见上面的引用),因此从逻辑上讲,它们没有所有权。理由似乎是编译器需要一个已知大小的数据结构:参考:
let s1: str = "foo"; // [rustc E0277] the size for values of type `str` cannot be known at compilation time [E]
字符串切片引用 (&str
) 不拥有它指向的字符串切片,而是借用它。您可以对一个对象有多个不可变引用,这就是为什么您的第二个代码示例是正确的并且借用检查器很乐意接受它的原因。
我想你可以说具有 'static
生命周期的类型没有所有者,或者 main
函数之外的东西拥有它。所有者仅在拥有对象的生命周期结束时才重要(如果拥有它,则需要释放资源)。仅供参考,生命周期很重要。