@@ -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,31 @@ 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 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
+
65
90
## Trait bound
66
91
67
92
As a trait bound, it means the type does not contain any non-static
0 commit comments