Coercion in Rust by Example

re: this example of lifetime coercion
https://doc.rust-lang.org/stable/rust-by-example/scope/lifetime/lifetime_coercion.html

I assumed that if I swapped the 1st and 2nd arguments to choose_first, I would get a compiler error or warning, but it actually runs ok:

>         println!("{} is the first", choose_first(&second, &first));
/// 3 is the first

So the comment

<'a: 'b, 'b> reads as lifetime 'a is at least as long as 'b.

is not exactly right because second has a shorter lifetime than first? What is going on here?
Thanks for any clarification.

PS, just learning, but really loving all the great Rust docs. Can’t wait to dive in.

What is happening is that Rust is choosing the lifetimes to be different that what is shown.

When you swap the parameters, you are changing the problem entirely. Also, you should note that lifetimes no longer correspond to lexical scopes, they correspond to invisible scopes that are determined by when values are used.

The statement that

<'a: 'b, 'b> reads as lifetime 'a is at least as long as 'b .

is true, and is necessary for correctness. If you would like to see an example of how this comes up in a more visible, but more complex and niche way, see my answer here

where I respond to this post

2 Likes

Thanks @KrishnaSannasi. This is a key concept I was missing:

lifetimes no longer correspond to lexical scopes, they correspond to invisible scopes that are determined by when values are used.

I appreciate your response in the other thread too. Will need to refer back to it as my studies continue. Bonus for your use of a Hitchhiker’s Guide to the Galaxy reference :slight_smile:

2 Likes

Ah, that wasn’t me, that was @dakom

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.