Skip to content
เข้าสู่ระบบ

Lifetime Patterns

Patterns สำหรับ lifetime management

// Function with lifetime
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { x } else { y }
}
// Multiple lifetimes
fn first_word<'a, 'b>(s: &'a str, _other: &'b str) -> &'a str {
s.split_whitespace().next().unwrap_or("")
}
fn main() {
let s1 = String::from("hello");
let s2 = String::from("world!");
let result = longest(&s1, &s2);
println!("Longest: {}", result);
// Lifetime scopes
let outer = String::from("outer");
{
let inner = String::from("inner string");
let result = longest(&outer, &inner);
println!("Result: {}", result); // OK: both strings valid
}
// inner dropped here
println!("Outer still valid: {}", outer);
}

เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม

ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด