簡體   English   中英

Rust 多生命周期結構無法訪問超出較短生命周期參數

[英]Rust multiple lifetimes struct can't access beyond the less longer lifetime parameter

struct TwoStrRef<'a, 'b> {
    str1: &'a str,
    str2: &'b str,
}

fn main() {
    let a_ref_struct;
    let string_1 = String::from("hello");
    let str_ref;
    {
        let string_2 = String::from("world");

        a_ref_struct = TwoStrRef {
            str1: &string_1,
            str2: &string_2,
        };

        str_ref = a_ref_struct.str1;
    }

    // str_ref; // Ok

    // a_ref_struct.str1;  // Error: `string_2` does not live long enough borrowed value does not live long enough
}

struct TwoStrRef有兩個生命周期參數a''b ,我將string_1string_2的引用(它們在不同的范圍內, string_1是更長的)分配給字段str_1str_2 ,當我嘗試訪問a_ref_struct.str1超出string_2的范圍(但與string_1相同),編譯器會拋出錯誤,這表明string_2的壽命不夠長。 str1字段不是包含不在其范圍之外的string_1的引用嗎? 為什么如果我將 str1 引用分配給str_ref ,我可以在與string_1相同的范圍內訪問它?

str1字段不是包含不在其范圍之外的string_1的引用嗎?

a_ref_structstring_2超出范圍之前被刪除:這是必需的,因為否則對其str2字段的任何訪問(例如,可能在其刪除處理程序中發生)都將無效。 實際上,如果在刪除string2之后存在a_ref_struct ,則它的str2將是對已釋放內存的引用,這是未定義的行為,即使該引用從未被訪問過。

為什么如果我將 str1 引用分配給str_ref ,我可以在與string_1相同的范圍內訪問它?

在那里,您只是獲取a_ref_struct.str1中保存的引用的副本(生命周期為'astring_1 )並將該副本存儲到str_ref中。 然后可以(並且是)刪除a_ref_struct而不會影響該(復制的)引用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM