Skip to content

Commit 11e1373

Browse files
authored
pedantic 'static lifetime corrections
1 parent 07e0df2 commit 11e1373

File tree

1 file changed

+26
-2
lines changed

1 file changed

+26
-2
lines changed

src/scope/lifetime/static_lifetime.md

Lines changed: 26 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,30 @@ 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 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
73+
use rand::Fill;
74+
75+
fn random_vec() -> &'static [usize; 100] {
76+
let mut rng = rand::thread_rng();
77+
let mut boxed = Box::new([0; 100]);
78+
boxed.try_fill(&mut rng).unwrap();
79+
Box::leak(boxed)
80+
}
81+
82+
fn main() {
83+
let first: &'static [usize; 100] = random_vec();
84+
let second: &'static [usize; 100] = random_vec();
85+
assert_ne!(first, second)
86+
}
87+
```
88+
6589
## Trait bound
6690

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

0 commit comments

Comments
 (0)