rust-lang / nomicon

The Dark Arts of Advanced and Unsafe Rust Programming
https://doc.rust-lang.org/nomicon/
Apache License 2.0
1.82k stars 262 forks source link

Expand unbounded lifetime example code and improve wording #408

Closed Enselic closed 1 year ago

Enselic commented 1 year ago

Due to wrapping, the diff looks larger than it is. I have only changed

The most common source of this is dereferencing a raw pointer, which produces a reference with an unbounded lifetime.

into the more accurate

The most common source of this is taking a reference to a dereferenced raw pointer, which produces a reference with an unbounded lifetime.

See Zulip discussion.

I have also expanded on the example code by expanding:

For instance:

fn get_str<'a>() -> &'a str;

will produce an &str with an unbounded lifetime.

into:

For instance:

fn get_str<'a>(s: *const String) -> &'a str {
    unsafe { &*s }
}

fn main() {
    let soon_dropped = String::from("hello");
    let dangling = get_str(&soon_dropped);
    drop(soon_dropped);
    println!("Invalid str: {}", dangling); // Invalid str: gӚ_`
}