RUST 静态生命周期和动态生命周期
图例分配在堆和栈上的内存有其各自的作用域它们的生命周期是动态的全局变量、静态变量、字符串字母量、代码等内容在编译时会被编译到可执行文件中的 BSS/Data/RoData/Text 段然后在加载时装入内存因而它们的生命周期和进程的生命周期一致所以静态的所以函数指针的生命周期也是静态因为函数在Text 段中只要进程活着其内存一直存在静态生命周期概述静态生命周期 Rust 中最长的生命周期表示引用在整个程序运行期间都有效。这些数据通常存储在程序的只读内存区域在程序启动时创建在程序结束时销毁特点数据存在于整个程序运行期间通常存储在静态内存区域不需要运行时生命周期检查最安全的引用类型示例// 字符串字面量具有 static 生命周期letstatic_str:staticstrHello, World!;// 静态变量也具有 static 生命周期staticSTATIC_INT:i3242;letstatic_ref:statici32STATIC_INT;// 函数返回 static 生命周期fnget_static_str()-staticstr{This string lives for the entire program}// 在结构体中使用 static 生命周期structStaticHolder{data:staticstr,}implStaticHolder{fnnew()-Self{StaticHolder{data:This data lives forever,}}}fnmain(){letholderStaticHolder::new();println!({},holder.data);letsget_static_str();println!({},s);// 这些引用可以在任何地方使用不会出现悬垂引用letlong_lived_refstatic_str;println!({},long_lived_ref);}动态生命周期概述动态生命周期是指哪些在编译时无法确定具体持续时间需要在运行时通过检查器验证的生命周期这些生命周期通常与作用域相关由编译器推断或通过生命周期参数明确指定特点生命周期在编译不确定需要运行时检查与特定作用域绑定需要生命周期注解来帮助编译器验证安全性更灵活但需要更多编译器支持例子// 函数接受两个引用并返回一个引用需要明确生命周期参数fnlongesta(x:astr,y:astr)-astr{ifx.len()y.len(){x}else{y}}// 结构体包含引用需要生命周期参数structTextEditora{content:astr,selection:astr,}implaTextEditora{fnnew(content:astr)-Self{TextEditor{content,selection:,}}fnselect(mutself,start:usize,end:usize){self.selectionself.content[start..end];}}fnmain(){// 动态生命周期的示例letstring1String::from(long string is long);letstring2String::from(short);letresult;{// 这两个引用有不同的生命周期letpart1string1;letpart2string2;// longest 函数要求两个参数有相同的生命周期 aresultlongest(part1,part2);println!(The longest string is: {},result);}// part1 和 part2 在这里离开作用域// result 仍然有效因为它引用的是 string1 或 string2 的一部分// 而 string1 和 string2 仍然在作用域内println!(Still can use: {},result);// 文本编辑器示例letcontentString::from(This is a long text content for the editor);letmuteditorTextEditor::new(content);editor.select(5,15);println!(Selection: {},editor.selection);// 如果尝试在 content 离开作用域后使用 editor会导致编译错误// {// let local_content String::from(local);// let local_editor TextEditor::new(local_content);// // local_editor 不能离开这个作用域因为它的引用依赖于 local_content// }// println!({:?}, local_editor); // 这会编译错误}总结特性静态生命周期 (static)动态生命周期持续时间整个程序运行期间由作用域决定内存位置静态内存区域栈或堆安全性绝对安全需要编译器验证灵活性低高使用场景字符串字面量、静态变量函数参数、结构体字段