Ownership และ Borrowing
Rust Lifetimes Explained
Tell the compiler how long a returned reference stays valid with 'a.
สิ่งที่คุณจะได้เรียนรู้
- What a lifetime is
- Annotating with 'a
- Lifetimes in structs
fn longest<'a>(a: &'a str, b: &'a str) -> &'a str
- 1
a: &'a strinput - 2
b: &'a strinput - 3
-> &'a strvalid as long as both inputs
References must not outlive their data
A lifetime describes how long a reference is valid. Most of the time the compiler works it out. When a function returns a reference that could come from more than one parameter, you name the lifetime with 'a.
The signature of longest says that the result lives as long as both inputs do. subtitle is a string literal, which lives for the whole program, so result is still valid after the inner block. A struct that stores a reference needs a lifetime too.
ประเด็นสำคัญ
- Most lifetimes are worked out by the compiler.
- 'a links the result to the inputs.
- A struct that stores a reference needs a lifetime.
ตัวอย่าง Rust ที่รันได้
Rust
main.rs
fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
if a.len() >= b.len() {
a
} else {
b
}
}
struct Highlight<'a> {
text: &'a str,
}
fn main() {
let title = String::from("The Rust Book");
let result;
{
let subtitle = "2021 edition";
result = longest(&title, subtitle);
}
println!("longest: {result}");
let highlight = Highlight { text: &title[4..8] };
println!("highlight: {}", highlight.text);
}
longest: The Rust Book
highlight: Rustฝึกฝน
เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์
เรียนบทนี้จบแล้วใช่ไหม
ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า
ความคืบหน้าของคุณถูกบันทึกไว้ในเบราว์เซอร์นี้ เข้าสู่ระบบเพื่อเก็บไว้ใช้ได้ทุกอุปกรณ์
ฝึกด้วยโจทย์
ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI
โจทย์ทั้งหมด