Chuyển đến nội dung chính
eLearner.app
Mô-đun 6 · Bài học 1 trong tổng số 211/14 trong khóa học~15 min
Bài học theo mô-đun (1/2)

Tuổi thọ và Tài liệu tham khảo

In Rust, every reference has a lifetime, which corresponds to the scope within which that reference is valid. Most of the time, lifetimes are implicit and inferred by the compiler thanks to lifetime elision rules. However, when the relationship between the lifetimes of different references is ambiguous, we must annotate them explicitly.

The main objective of lifetimes is to prevent dangling references (references to data that has already been deallocated from memory).


Lifetime Annotation Syntax

Lifetime names start with an apostrophe (') and are usually short lowercase letters (like 'a). Lifetime annotations do not change the actual lifetime of variables, but they indicate to the compiler the relationship between the validity of inputs and outputs.

For example, if a function takes two string reference parameters and returns a string reference, and we want the returned reference to be valid as long as both input parameters are valid, we use:

Code
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() > y.len() {
        x
    } else {
        y
    }
}

Lifetimes in Data Structures

If a structure contains a field that is a reference, we must explicitly annotate the lifetime on that reference to ensure that the struct instance cannot outlive the data it refers to:

Code
struct ImportantExcerpt<'a> {
    part: &'a str,
}

fn main() {
    let novel = String::from("Call me Ishmael. Some years ago...");
    let first_sentence = novel.split('.').next().unwrap();
    let i = ImportantExcerpt {
        part: first_sentence,
    };
}

The Static Lifetime

The 'static lifetime is a special lifetime that lasts for the entire duration of the program. All string literals (&str) implicitly have a 'static lifetime because they are stored directly inside the binary executable.

Code
let s: &'static str = "I have a static lifetime.";

Try it yourself

Exercise 1: The longest function

tập thể dục#rust.m6.l1.e1
Nỗ lực: 0Đang tải…

Write a function named longest<'a> that accepts two parameters, x of type &'a str and y of type &'a str, and returns a value of type &'a str. Inside the function, use an if/else block to return x if its length is greater than y, otherwise return y.

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

Declare the signature with `fn longest<'a>(x: &'a str, y: &'a str) -> &'a str`. Then use `if x.len() > y.len() { x } else { y }`.

Giải pháp khả dụng sau 3 lần thử

Exercise 2: Structs with References

tập thể dục#rust.m6.l1.e2
Nỗ lực: 0Đang tải…

Define a structure named Excerpt<'a> containing a single field named part of type &'a str. In the main function, create a string variable named text and instantiate a variable excerpt of type Excerpt by borrowing a reference to text. Print excerpt.part.

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

Use `struct Excerpt<'a> { part: &'a str }`. In main instantiate it with `Excerpt { part: &text }`.

Giải pháp khả dụng sau 3 lần thử

Exercise 3: Static References

tập thể dục#rust.m6.l1.e3
Nỗ lực: 0Đang tải…

Declare a variable named message with an explicit type annotation for the static lifetime (&'static str), assigning it a string literal. Print the value of message.

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

Use the syntax `let message: &'static str = 'Messaggio statico!';` to explicitly annotate the static lifetime.

Giải pháp khả dụng sau 3 lần thử