Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Rust Lifetimes

Rust Lifetimes

Rust's lifetime mechanism is a resource management mechanism as important as ownership.

This concept was introduced mainly to deal with resource management problems in complex type systems.

References are an essential mechanism when dealing with complex types, after all, data of complex types cannot be easily copied and computed by the processor.

But references often lead to extremely complex resource management problems; let's first look at dangling references:

Example

{

   

let

r

;

   

{

       

let

x

=

5

;

        r

=

&

x

;

   

}

    println

!

(

"r: {}"

,

r

)

;

}

This code will not pass the Rust compiler because the value referenced by r has already been freed before use.

The green range 'a in the figure above represents r's lifetime, and the blue range 'b represents x's lifetime. Obviously, 'b is much smaller than 'a; a reference is only valid within the lifetime of the value.

We have always used String instead of &str in structs; let's explain the reason with a case:

Example

fn

longer

(

s1

:

&

str

,

s2

:

&

str

)

->

&

str

{

   

if

s2.len

(

)

s1.len

(

)

{

        s2

   

}

else

{

        s1

   

}

}

The longer function takes the longer of two string slices s1 and s2 and returns a reference to it. But this code won't compile, because the returned reference might be a stale reference:

Example

fn

main

(

)

{

   

let

r

;

   

{

       

let

s1

=

"rust"

;

       

let

s2

=

"ecmascript"

;

        r

=

longer

(

s1

,

s2

)

;

   

}

    println

!

(

"{} is longer"

,

r

)

;

}

In this program, although a comparison was made, when r is used the source values s1 and s2 are already invalid. Of course, we could move the use of r within the lifetime range of s1 and s2 to prevent this error, but a function cannot know the situation outside itself; to guarantee that the value it passes out is valid, it must follow the ownership principle to eliminate all danger, so the longer function cannot compile.

Lifetime annotations

Lifetime annotations are a way to describe the lifetime of references.

Although this cannot change the lifetime of a reference, it can declare in appropriate places that two references have the same lifetime.

A lifetime annotation starts with a single quote followed by a lowercase letter word:

&i32        // 常规引用

&'a i32     // 含有生命周期注释的引用

&'a mut i32 // 可变型含有生命周期注释的引用

Let's modify the longer function using lifetime annotations:

Example

fn

longer

<

'a>(s1: &'

a

str

,

s2

:

&

'a str) -> &'

a

str

{

   

if

s2.len

(

)

s1.len

(

)

{

        s2

   

}

else

{

        s1

   

}

}

We need to use a generic declaration to specify the lifetime name; then the function's return value lifetime will be consistent with the lifetimes of the two parameters, so when calling it you can write:

Example

fn

main

(

)

{

   

let

r

;

   

{

       

let

s1

=

"rust"

;

       

let

s2

=

"ecmascript"

;

        r

=

longer

(

s1

,

s2

)

;

        println

!

(

"{} is longer"

,

r

)

;

   

}

}

The combined running result of the two programs above:

ecmascript is longer

**Note:** Don't forget the principle of automatic type inference.

Using string slice references in structs

This is a question left earlier, answered here:

Example

fn

main

(

)

{

   

struct

Str

<

'a> {
        content: &'

a

str

   

}

   

let

s

=

Str

{

        content

:

"string_slice"

   

}

;

    println

!

(

"s.content = {}"

,

s.content

)

;

}

Running result:

s.content = string_slice

If a method is defined for struct Str:

Example

impl

<

'a> Str<'

a

{

   

fn

get_content

(

&

self

)

->

&

str

{

       

self

.content

   

}

}

The return value here has no lifetime annotation, but adding one wouldn't hurt. This is a historical issue: early Rust did not support automatic lifetime inference, so all lifetimes had to be strictly declared, but mainstream stable versions of Rust already support this feature.

Static lifetime

There is a special lifetime annotation: 'static. The exact data type of all string constants enclosed in double quotes is &'static str; the lifetime represented by 'static lasts from the start of program execution to the end.

Generics, traits, and lifetimes working together

Example

use

std

::

fmt

::

Display

;

fn

longest_with_an_announcement

<

'a, T>(x: &'

a

str

,

y

:

&

'a str, ann: T) -> &'

a

str

    where T

:

Display

{

    println

!

(

"Announcement! {}"

,

ann

)

;

   

if

x.len

(

)

y.len

(

)

{

        x

   

}

else

{

        y

   

}

}

This program comes from the Rust Bible; it uses generics, traits, and lifetime mechanisms all at once. It's not mandatory, but you can try it out—after all, you'll need it sooner or later!