// 定义一个结构体
struct MyStruct<'a> {
// 字符串切片,生命周期为 'a
first: &'a str,
// 指向 first 的引用,生命周期也为 'a
second_ref: &'a str,
}
fn main() {
let my_string = String::from("Hello, World!");
// 初始化结构体
let my_struct = MyStruct {
first: &my_string,
second_ref: &my_string,
};
println!("First: {}, Second: {}", my_struct.first, my_struct.second_ref);
}
生命周期协同工作解释
- 结构体定义:在
struct MyStruct<'a>
中,定义了一个生命周期参数 'a
。这表明结构体内部的所有引用都依赖于这个统一的生命周期 'a
。
- 成员定义:
first
是一个 &'a str
类型的字符串切片,其生命周期为 'a
。second_ref
是指向 first
的引用,同样具有生命周期 'a
。这确保了 second_ref
引用的对象在其生命周期内不会被释放,避免了悬垂引用问题。
- 初始化过程:在
main
函数中,创建了一个 String
类型的 my_string
。然后使用 my_string
的引用初始化 MyStruct
实例。因为 my_string
的生命周期覆盖了 my_struct
的整个使用范围,所以满足了 MyStruct
中所有引用的生命周期要求。这样就确保了在 my_struct
使用过程中,first
和 second_ref
所引用的对象始终有效,避免了悬垂引用。