簡體   English   中英

<'a,'b:'a>是否意味着生命周期'b必須比生命周期更長'a?

[英]Does <'a, 'b: 'a> mean that the lifetime 'b must outlive the lifetime 'a?

我想實現一個類似於標准庫定義的調試構建器的構建器。 它們使用如下結構定義:

struct DebugFoo<'a, 'b: 'a> {
    fmt: &'a mut std::fmt::Formatter<'b>
}

因為我不明白什么形式<'a, 'b: 'a>意味着我也不能在Rust書或Rust參考文獻中找到它(至少關於生命期),我只是試圖刪除我不喜歡的內容了解發生了什么:

struct DebugFoo<'a, 'b> {
    fmt: &'a mut std::fmt::Formatter<'b>
}

編譯它我得到這個錯誤:

in type `&'a mut core::fmt::Formatter<'b>`, reference has a longer 
lifetime than the data it references

而且這個說明:

the pointer is valid for the lifetime 'a as defined on the struct at 1:0
but the referenced data is only valid for the lifetime 'b as defined on
the struct at 1:0

這是有道理的對我說: 'a'b是不同的生命周期的話,要在安全方面,拉斯特(?借檢查)假設'a會活得比'b ,並拋出錯誤。

現在我可以猜測<'a, 'b: 'a>意味着生命周期'b必須長於生命周期'a 我猜對了嗎? 還是還有更多? 我怎樣才能找到它?

冒號讀作“outlives”,所以

'long: 'short

讀“ 'long壽命比'short ”。

至於關於該主題的官方文檔,到目前為止我唯一記錄的地方是關於生命界限RFC

是的,你是對的。

一個綁定<...: 'a>意味着, ... (任一類型或另一種壽命)需要能夠活得比'a 例如'b: 'a表示“ 'b必須至少與'a一樣長壽(但不是嚴格過時,但它們可以是相同的)。

暫無
暫無

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

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