函式呼叫中的生命週期
參照的「生命週期」不得「超過」其所參照的值。此由借用檢查器負責驗證。
按照我們目前所見,生命週期可以隱晦表示。不過,&'a Point
、&'document str
也可以明確表示生命週期。生命週期的開頭為 '
,一般預設名稱為 'a
。請將 ``&'a Point讀做「至少對生命週期
a有效的借用
Point`」。
Lifetimes are always inferred by the compiler: you cannot assign a lifetime yourself. Explicit lifetime annotations create constraints where there is ambiguity; the compiler verifies that there is a valid solution.
在考慮與函式間傳遞值時,生命週期會變得比較複雜。
Speaker Notes
This slide should take about 10 minutes.
在本例中,編譯器無法堆論出 p3
到底有多長的生命週期。查看函式主體內部後顯示,編譯器只有把握假設 p3
的生命週期是 p1
和 p2
中的較短那個。但就像型別一樣,Rust 規定要對函式引數和回傳值的生命週期加上明確註解。
請將 'a
妥善新增至 left_most
:
fn left_most<'a>(p1: &'a Point, p2: &'a Point) -> &'a Point {
這表示,「假設 p1 和 p2 都比 'a
長」,回傳值的生命週期至少會為 'a
。
一般情況下可以省略生命週期,詳情請見下一張投影片。