在 static 和 const 中的更简单的生命周期

Minimum Rust version: 1.17

在以往的 Rust 中,在需要的时候,你必须更加明确的在 static 或者 const 上写明 'static 生命周期。

1. # mod foo {
2. const NAME: &'static str = "Ferris";
3. # }
4. # mod bar {
5. static NAME: &'static str = "Ferris";
6. # }

但是,在这里 'static 是唯一一种可能的生命周期,所以现在你可以不用再写 'static 了:

1. # mod foo {
2. const NAME: &str = "Ferris";
3. # }
4. # mod bar {
5. static NAME: &str = "Ferris";
6. # }

在某些场景下,这个可以消除很多累赘:

1. # mod foo {
2. // old
3. const NAMES: &'static [&'static str; 2] = &["Ferris", "Bors"];
4. # }
5. # mod bar {

7. // new
8. const NAMES: &[&str; 2] = &["Ferris", "Bors"];
9. # }