![](/img/trans.png)
[英]Why can borrowed string literal outlive its owner by faking a lifetime?
[英]Extending borrowed lifetime for String slice
我有一個讀取文件的函數,並且每行都將它添加到類型為&str
的HashSet
中,但是我無法弄清楚如何告訴借用檢查器增加生命周期。
到目前為止,這是我的功能:
fn build_collection_set(reader: &mut BufReader<File>) -> HashSet<&str> {
let mut collection_set: HashSet<&str> = HashSet::new();
for line in reader.lines() {
let line = line.unwrap();
if line.len() > 0 {
collection_set.insert(&*line);
}
}
return collection_set;
}
我怎么讓Rust知道我想要更長時間保持它?
但我無法弄清楚如何告訴借閱檢查員增加壽命。
不可能。
C,C ++或Rust中的值的生命周期定義為:
您可以創建引用此值的變量,如果您的引用長於值,則您有一個懸空引用:
為了驗證您的程序,Rust編譯器將要求您注釋引用的生命周期; 您將使用生命周期注釋,例如'a
in &'a T
允許命名生命周期,以記錄多個值的生命周期之間的關系。
操作詞是這里的文檔 :生命是無形的,不能受到影響,生命周期注釋'a
只是一個允許引用它的名稱。
所以?
每當您發現自己想要延長引用的生命周期時,您應該關注的是延長引用的生命周期...或者根本不使用引用而是使用值。
在這種情況下,一個簡單的解決方案是返回String
而不是&str
:
fn build_collection_set(reader: &mut BufReader<File>) -> HashSet<String> {
let mut collection_set = HashSet::new();
for line in reader.lines() {
let line = line.unwrap();
if line.len() > 0 {
collection_set.insert(line);
}
}
collection_set
}
reader.lines()
返回擁有的字符串的迭代器。 但是在你的for循環中,你將它們轉換為對&str
借用引用。 因此,當迭代器超出范圍時,所有借用的引用都將變為無效。 考慮使用HashSet<String>
,這也是零成本,因為字符串被移動到HashSet中,因此不會被復制。
fn build_collection_set(reader: &mut BufReader<File>) -> HashSet<String> {
let mut collection_set: HashSet<String> = HashSet::new();
for line in reader.lines() {
let line = line.unwrap();
if line.len() > 0 {
collection_set.insert(line);
}
}
collection_set
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.