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

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

Open
pwbh opened this issue Sep 27, 2023 · 0 comments

Comments

@pwbh
Copy link

pwbh commented Sep 27, 2023

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.

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

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant