【Rust】生命周期
生命周期
当函数签名中没有显式生命周期参数时,Rust 会根据以下三条规则自动推断:
1. 每个引用参数都有自己的生命周期参数。
例如,函数有两个引用参数,Rust 会假设它们有不同的生命周期:
fn foo(x: &i32, y: &i32) -> i32 { ... }
// 自动推断为:
fn foo<'a, 'b>(x: &'a i32, y: &'b i32) -> i32 { ... }
2. 如果只有一个输入生命周期参数,那么所有输出生命周期都使用这个生命周期。
fn first_word(s: &str) -> &str { ... }
// 自动推断为:
fn first_word<'a>(s: &'a str) -> &'a str { ... }
3. 如果有多个输入生命周期参数,但其中一个是 &self 或 &mut self,那么所有输出生命周期都使用 self 的生命周期。
impl<'a> SomeStruct<'a> {
fn get_ref(&self) -> &str { ... }
}
// 自动推断为:
fn get_ref<'a>(&'a self) -> &'a str { ... }
| 用法 | 示例 |
|---|---|
| 显式生命周期参数 | <'a> |
| 应用于引用类型 | &'a str, &'a T |
| 函数参数/返回值标注 | fn foo<'a>(x: &'a T) -> &'a T |
// 结构体定义:包含对字符串切片的引用
struct TextSnippet<'a> {
content: &'a str,
}
impl<'a> TextSnippet<'a> {
// 返回引用的长度
fn len(&self) -> usize {
self.content.len()
}
// 判断是否包含某个子串
fn contains(&self, word: &str) -> bool {
self.content.contains(word)
}
// 返回原始内容
fn content(&self) -> &'a str {
self.content
}
}
fn main() {
let text = String::from("Rust makes systems programming safe and fun.");
// 截取一部分,注意:是 &str 类型,生命周期依赖 text
let snippet_part = &text[5..30]; // "makes systems programming"
// 使用结构体封装引用
let snippet = TextSnippet {
content: snippet_part,
};
println!("Snippet: {}", snippet.content());
println!("Length: {}", snippet.len());
println!("Contains 'systems'? {}", snippet.contains("systems"));
}

浙公网安备 33010602011771号