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

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

Closed
heftig opened this issue May 23, 2020 · 2 comments
Closed

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

heftig opened this issue May 23, 2020 · 2 comments

Comments

@heftig
Copy link

heftig commented May 23, 2020

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

@pretzelhammer
Copy link
Owner

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
Copy link
Owner

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

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

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

2 participants