Why are explicit lifetimes needed in Rust?

前端 未结 10 1191
别那么骄傲
别那么骄傲 2020-11-22 16:08

I was reading the lifetimes chapter of the Rust book, and I came across this example for a named/explicit lifetime:

struct Foo<\'a> {
    x: &\'a i         


        
10条回答
  •  孤城傲影
    2020-11-22 16:40

    If a function receives two references as arguments and returns a reference, then the implementation of the function might sometimes return the first reference and sometimes the second one. It is impossible to predict which reference will be returned for a given call. In this case, it is impossible to infer a lifetime for the returned reference, since each argument reference may refer to a different variable binding with a different lifetime. Explicit lifetimes help to avoid or clarify such a situation.

    Likewise, if a structure holds two references (as two member fields) then a member function of the structure may sometimes return the first reference and sometimes the second one. Again explicit lifetimes prevent such ambiguities.

    In a few simple situations, there is lifetime elision where the compiler can infer lifetimes.

提交回复
热议问题