Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pedantic 'static lifetime corrections #1732

Merged
merged 5 commits into from
Aug 22, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 27 additions & 2 deletions src/scope/lifetime/static_lifetime.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@ confusion when learning Rust. Here are some examples for each situation:
## Reference lifetime

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

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

* Make a constant with the `static` declaration.
Expand Down Expand Up @@ -62,6 +62,31 @@ fn main() {
}
```

Since `'static` references only need to be valid for the _remainder_ of
a program's life, they can be created while the program is executed. Just to
demonstrate, the below example uses
[`Box::leak`](https://doc.rust-lang.org/std/boxed/struct.Box.html#method.leak)
to dynamically create `'static` references. In that case it definitely doesn't
live for the entire duration, but only for the leaking point onward.

```rust,editable,compile_fail
extern crate rand;
use rand::Fill;
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd like to note that the rust playground allows use of the top 100 most downloaded crates, allowing rand to be used here


fn random_vec() -> &'static [usize; 100] {
let mut rng = rand::thread_rng();
let mut boxed = Box::new([0; 100]);
boxed.try_fill(&mut rng).unwrap();
Box::leak(boxed)
}

fn main() {
let first: &'static [usize; 100] = random_vec();
let second: &'static [usize; 100] = random_vec();
assert_ne!(first, second)
}
```

## Trait bound

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