简体   繁体   English

在Rust中,你能拥有一个字符串文字吗?

[英]In Rust, can you own a string literal?

According to The Rust book : 根据The Rust书

Each value in Rust has a variable that's called its owner. Rust中的每个值都有一个称为其所有者的变量。 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 : 根据rust-lang.org

Static items do not call drop at the end of the program. 静态项目不会在程序结束时调用drop。

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 . 在阅读了这篇SO帖子 ,并给出了下面的代码后,我理解foo是一个值,其变量y ,相当于&y因为“字符串文字是字符串切片” ,称为其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 . 我想知道因为与拥有的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")
}

UPDATE: According to The Rust book : 更新:根据The Rust书

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. 由于字符串文字是字符串切片( &str )(参见上面的引用),因此它们在逻辑上没有所有权。 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. 字符串切片引用( &str )不拥有它指向的字符串切片,它借用它。 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. 我想你可以说具有'static生命周期的类型没有所有者,或者main功能之外的东西拥有它。 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. 仅供参考,寿命很重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM