Skip to content

Commit e045778

Browse files
authored
Merge pull request #1732 from k12ish/patch-1
Pedantic `'static` lifetime corrections
2 parents 07e0df2 + 3e2fb19 commit e045778

File tree

1 file changed

+27
-2
lines changed

1 file changed

+27
-2
lines changed

src/scope/lifetime/static_lifetime.md

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,10 @@ confusion when learning Rust. Here are some examples for each situation:
1717
## Reference lifetime
1818

1919
As a reference lifetime `'static` indicates that the data pointed to by
20-
the reference lives for the entire lifetime of the running program.
20+
the reference lives for the remaining lifetime of the running program.
2121
It can still be coerced to a shorter lifetime.
2222

23-
There are two ways to make a variable with `'static` lifetime, and both
23+
There are two common ways to make a variable with `'static` lifetime, and both
2424
are stored in the read-only memory of the binary:
2525

2626
* Make a constant with the `static` declaration.
@@ -62,6 +62,31 @@ fn main() {
6262
}
6363
```
6464

65+
Since `'static` references only need to be valid for the _remainder_ of
66+
a program's life, they can be created while the program is executed. Just to
67+
demonstrate, the below example uses
68+
[`Box::leak`](https://doc.rust-lang.org/std/boxed/struct.Box.html#method.leak)
69+
to dynamically create `'static` references. In that case it definitely doesn't
70+
live for the entire duration, but only for the leaking point onward.
71+
72+
```rust,editable,compile_fail
73+
extern crate rand;
74+
use rand::Fill;
75+
76+
fn random_vec() -> &'static [usize; 100] {
77+
let mut rng = rand::thread_rng();
78+
let mut boxed = Box::new([0; 100]);
79+
boxed.try_fill(&mut rng).unwrap();
80+
Box::leak(boxed)
81+
}
82+
83+
fn main() {
84+
let first: &'static [usize; 100] = random_vec();
85+
let second: &'static [usize; 100] = random_vec();
86+
assert_ne!(first, second)
87+
}
88+
```
89+
6590
## Trait bound
6691

6792
As a trait bound, it means the type does not contain any non-static

0 commit comments

Comments
 (0)