Why is adding a lifetime to a trait with the plus operator (Iterator<Item = &Foo> + &#39;a) needed?

*爱你&永不变心* 提交于 2019-11-26 11:24:38
Lukas Kalbertodt

There is one thing that is easily overlooked: if you have a trait Foo and you want to have a boxed trait object Box<Foo>, the compiler automatically adds a 'static lifetime bound (as specified in RFC 599). This means that Box<Foo> and Box<Foo + 'static> are equivalent!

In your case, the compiler automatically adds the static bound such that this ...

fn into_iterator(myvec: &Vec<Foo>) -> Box<Iterator<Item = &Foo>>

... is equivalent to that:

fn into_iterator(myvec: &Vec<Foo>) -> Box<Iterator<Item = &Foo> + 'static>

Now lifetime elision rules kick in and "connect" the two lifetime-slots, such that the above code is equivalent to:

fn into_iterator<'a>(myvec: &'a Vec<Foo>) -> Box<Iterator<Item = &'a Foo> + 'static>

But the type Iter<'a, Foo> (the specific iterator type for Vec<Foo>) obviously does not satisfy the bound 'static (because it is borrowing the Vec<Foo>)! So we have to tell the compiler that we don't want the default 'static bound by specifying our own lifetime bound:

fn into_iterator<'a>(myvec: &'a Vec<Foo>) -> Box<Iterator<Item = &Foo> + 'a>

Now the compiler knows that the trait object is only valid for the lifetime 'a. Note that we don't explicitly need to annotate the lifetime of the associated Item type! Lifetime elision rules take care of that.

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