pretzelhammer / rust-blog

Educational blog posts for Rust beginners
Apache License 2.0
7.11k stars 380 forks source link

`fn get_str<'a>() -> &'a str;` isn't pointlessly generic #4

Closed heftig closed 4 years ago

heftig commented 4 years ago

There's an actual difference between fn get_str<'a>() -> &'a str; and fn get_str() -> &'static str;. There wasn't until https://github.com/rust-lang/rust/pull/42417 got merged, but since then <'a> will work in some cases where a simple 'static will not.

pretzelhammer commented 4 years ago

Wow, nice find. I'll fix the "pointlessly generic" comment to say something else, but I'm wondering if this warrants its own section in the article.

Almost everyone, myself included, thinks "I can use a 'static ref where an 'a ref is expected"... but that is surprisingly not true in all cases. To import the example from the issue you linked:

fn static_bar() -> &'static str { "bar" }
fn generic_bar<'a>() -> &'a str { "bar" }

fn main() {
    let s = String::from("foo");
    Some(&s[..]).unwrap_or_else(generic_bar); // compiles
    Some(&s[..]).unwrap_or_else(static_bar); // compile error
}

I'll think over how I wanna introduce this information into the article, and what amendments I might have to make. Thanks for bringing this to my attention!

pretzelhammer commented 4 years ago

I've add a new section to my article specifically addressing this oddity.

I'm closing this issue as I now consider it completed.