How do lifetime bounds on structs work in Rust?

放肆的年华 提交于 2019-12-05 17:29:06

Lifetime parameters on references are contravariant: they can be substituted with a shorter lifetime when necessary.

Basically, you've got it the wrong way around. When you have a &'one Bar, you cannot assign a reference to a value with a shorter lifetime (such as 'two here), otherwise the reference would be dangling when execution leaves the 'two scope. However, when you have a &'two Bar, you can assign a reference to a value with a longer lifetime (such as 'one and 'static), because the reference will go out of scope before the referent does.

Why does your program compile? The compiler doesn't only use information from the calls to factory to select the appropriate lifetime; it also uses information from the assignments. &a has type &'one Bar and &b has type &'two Bar. Because 'two starts after 'one and ends before 'one, the compiler can coerce a &'one Bar to a &'two Bar. In object-oriented terms, a &'one Bar is a &'two Bar (&'one Bar is a subtype of &'two Bar). Just like how in Java, you can pass a String as an argument to a function that expects an Object. It's just that the subtyping relation is the other way around for lifetimes.

This means that we've found a common type for &a and &b: &'two Bar. Therefore, the compiler infers 'two for 'a in the calls to factory.

Note that the type of foo2 doesn't change at the assignment; the type of a value is always static.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!