rust-lang / nomicon

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

Add an elided bound example in unbounded lifetimes section to make stuff clearer #422

Open pwbh opened 9 months ago

pwbh commented 9 months ago

In the book written, quoting:

any output lifetimes that don't derive from inputs are unbounded

which refers to the following function of what not to do.

https://github.com/rust-lang/nomicon/blob/ddfa4214487686e91b21aa29afb972c08a8f0d5b/src/unbounded-lifetimes.md?plain=1#L22-L24

My suggestion is to add after the following quote:

The easiest way to avoid unbounded lifetimes is to use lifetime elision at the function boundary.

A "correct" code example to make stuff clearer, something like:

// lifetime 'a in input and output are elided. Bounded.
fn get_str(s: &str) -> &str {
    &s
}

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

If this seems logical enough for you, I'd be more then happy to create a PR.