pretzelhammer / rust-blog

Educational blog posts for Rust beginners
Apache License 2.0
7.58k stars 401 forks source link

Request for additional example in closure/function lifetime elision distinction #51

Closed bstrie closed 7 months ago

bstrie commented 3 years ago

From here: https://github.com/pretzelhammer/rust-blog/blob/master/posts/common-rust-lifetime-misconceptions.md#10-closures-follow-the-same-lifetime-elision-rules-as-functions

There's no good reason for this discrepancy. Closures were first implemented with different type inference semantics than functions and now we're stuck with it forever because to unify them at this point would be a breaking change.

Would it be a breaking change? I'm struggling to come up with a example of a closure that currently compiles that would no longer compile if the elision rules were changed to match functions. A one-line example of such a closure would be illustrative and unobtrusive here. And in the event that the claim is mistaken, that would bode well for changing the language to remove this discrepancy.

bstrie commented 3 years ago

Ah, here's an example:

fn foo(s: &str) -> &str {
    let bar = |_| { s };
    bar(&String::new())
}

The elision rules assign the same lifetime to the input and output of foo, but if they were to do the same for bar then the code would fail to compile, because the input to bar and the output of bar have different lifetimes.

pretzelhammer commented 7 months ago

I'll close this since it seems like you answered your own question.