Lifetime Patterns
Patterns สำหรับ lifetime management
Basic Lifetime Annotation
Section titled “Basic Lifetime Annotation”// Function with lifetimefn longest<'a>(x: &'a str, y: &'a str) -> &'a str { if x.len() > y.len() { x } else { y }}
// Multiple lifetimesfn 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 เพื่อปลดล็อกบทความทั้งหมด
Login with Google