'static 是一个 Rust 保留的生命周期名称,在之前我们可能已经见过好几次了:
// 引用的生命周期是 'static :
let s: &'static str = "hello world";
// 'static 也可以用于特征约束中:
fn generic<T>(x: T) where T: 'static {}
虽然它们都是 'static ,但是也稍有不同。
&'static
作为一个引用生命周期, &'static 说明该引用指向的数据可以跟程序活得一样久,但是该引用的生命周
期依然有可能被强转为一个更短的生命周期。
1. 🌟🌟 有好几种方法可以将一个变量标记为 'static 生命周期, 其中两种都是和保存在二进制文件中
相关( 例如字符串字面量就是保存在二进制文件中,它的生命周期是 'static )。
/* 使 用 两 种 方 法 填 空 */
fn main() {
__;
need_static(v);
println!("Success!")
}
fn need_static(r : &'static str) {
assert_eq!(r, "hello");
}
2. 🌟🌟🌟🌟 使用 Box::leak 也可以产生 'static 生命周期
#[derive(Debug)]
struct Config {
a: String,
b: String,
}
static mut config: Option<&mut Config> = None;
/* 让 代 码 工 作 , 但 不 要 修 改 函 数 的 签 名 */
fn init() -> Option<&'static mut Config> {
Some(&mut Config {
a: "A".to_string(),
b: "B".to_string(),
})
}
fn main() {
unsafe {
config = init();
println!("{:?}",config)
}
}
3. 🌟 &'static 只能说明引用指向的数据是能一直存活的,但是引用本身依然受限于它的作用域
fn main() {
{
// 字 符 串 字 面 量 能 跟 程 序 活 得 一 样 久 , 因 此 `static_string` 的 生 命 周 期 是 `'static`
let static_string = "I'm in read-only memory";
println!("static_string: {}", static_string);
// 当 `static_string` 超 出 作 用 域 时 , 该 引 用 就 无 法 再 被 使 用 , 但 是 引 用 指 向 的 数 据( 字 符
}
println!("static_string reference remains alive: {}", static_string);
}
4. &'static 可以被强转成一个较短的生命周期
Example
// 声 明 一 个 static 常 量 , 它 拥 有 `'static` 生 命 周 期.
static NUM: i32 = 18;
// 返 回 常 量 `Num` 的 引 用 , 注 意 , 这 里 的 生 命 周 期 从 `'static` 强 转 为 `'a`
fn coerce_static<'a>(_: &'a i32) -> &'a i32 {
&NUM
}
fn main() {
{
let lifetime_num = 9;
let coerced_static = coerce_static(&lifetime_num);
println!("coerced_static: {}", coerced_static);
}
println!("NUM: {} stays accessible!", NUM);
}