@@ -17,10 +17,10 @@ confusion when learning Rust. Here are some examples for each situation:
17
17
## Reference lifetime
18
18
19
19
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.
21
21
It can still be coerced to a shorter lifetime.
22
22
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
24
24
are stored in the read-only memory of the binary:
25
25
26
26
* Make a constant with the ` static ` declaration.
@@ -62,6 +62,30 @@ fn main() {
62
62
}
63
63
```
64
64
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
+
65
89
## Trait bound
66
90
67
91
As a trait bound, it means the type does not contain any non-static
0 commit comments