在 Rust 中,你能拥有一个字符串字面量吗? [英] In Rust, can you own a string literal?
问题描述
根据 Rust 书:
<块引用>Rust 中的每个值都有一个变量,称为其所有者.一次只能有一个所有者.当所有者超出范围时,该值将被删除.
根据 rust-lang.org:><块引用>
静态项目不会在程序结束时调用 drop.
阅读这篇SO帖子后,并给出下面的代码,我明白foo
是一个值,其变量 y
,等价于 &y
,因为 "字符串文字是字符串切片",称为它的owner
.那是对的吗?还是静态项目没有所有者?
let x = String::from("foo");//堆已分配,可变,拥有let y = "foo"//静态分配给 rust 可执行文件,不可变
我想知道,因为与拥有的 String
不同,字符串文字不会移动,大概是因为它们是 存储在可执行文件中的.rodata
.
fn main() {让 s1 = "foo";//与 String::from("foo") 相反让 s2 = s1;//未移动让 s3 = s2;//没有错误,不像 String::from("foo")}
更新:根据 The Rust book:
<块引用>这些 & 符号是引用,它们允许您引用某个值而无需获得它的所有权...另一种没有所有权的数据类型是切片.
由于字符串文字是字符串切片 (&str
)(请参阅上面的引文),因此从逻辑上讲,它们没有所有权.理由似乎是编译器需要一个已知大小的数据结构:一个引用:
let s1: str = "foo";//[rustc E0277] 在编译时无法知道类型为 `str` 的值的大小 [E]
字符串切片引用 (&str
) 不拥有它指向的字符串切片,而是借用了它.您可以有多个对一个对象的不可变引用,这就是为什么您的第二个代码示例是正确的,借用检查器很乐意接受它.
我认为你可以说具有 'static
生命周期的类型没有所有者,或者 main
函数之外的东西拥有它.所有者仅在拥有对象的生命周期结束时才重要(如果您拥有它,则需要释放资源).对于引用,只有生命周期很重要.
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]
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.
这篇关于在 Rust 中,你能拥有一个字符串字面量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!