静态
Rust 有几个保留的生命周期名称。其中之一是 'static
。你可能在两种情况下遇到它:
这两种情况虽然相关但有微妙的区别,这也是学习 Rust 时常见的困惑来源。以下是每种情况的一些例子:
引用生命周期
作为引用生命周期,'static
表示该引用指向的数据在程序的整个剩余运行期间都有效。它仍然可以被强制转换为更短的生命周期。
有两种常见的方法可以创建具有 'static
生命周期的变量,它们都存储在二进制文件的只读内存中:
- 使用
static
声明创建一个常量。 - 创建一个字符串字面量,其类型为:
&'static str
。
请看下面的例子,展示了这些方法:
Since 'static
references only need to be valid for the remainder of a program's life, they can be created while the program is executed. Just to demonstrate, the below example uses Box::leak
to dynamically create 'static
references. In that case it definitely doesn't live for the entire duration, but only from the leaking point onward.
Trait 约束
作为 trait 约束时,它表示该类型不包含任何非静态引用。例如,接收者可以随意持有该类型,直到主动丢弃之前,它都不会变为无效。
理解这一点很重要:任何拥有所有权的数据总是满足 'static
生命周期约束,但对该数据的引用通常不满足:
编译器会提示你:
error[E0597]: `i` does not live long enough
--> src/lib.rs:15:15
|
15 | print_it(&i);
| ---------^^--
| | |
| | borrowed value does not live long enough
| argument requires that `i` is borrowed for `'static`
16 | }
| - `i` dropped here while still borrowed