为什么我可以在一种情况下详细介绍返回类型的寿命,而另一种情况需要明确选择寿命?
在这里,我必须给出 app
全生寿期,并且不能( app<'_>
):
struct App<'a> {
items: StatefulList<'a, (&'a str, &'a str, usize)>,
}
impl App<'_> {
fn new<'a>(items: &'a Vec<(&'a str, &'a str, usize)>) -> App<'a> {
App {
items: StatefulList::with_items(items),
}
}
}
如果我仅指定外部的寿命,它也有效vec
:
fn new<'a>(items: &'a Vec<(&str, &str, usize)>) -> App<'a>
如果我尝试将其列出,它给出( Playground ):
error[E0106]: missing lifetime specifier
--> src/lib.rs:18:53
|
18 | fn new(items: &Vec<(&str, &str, usize)>) -> App<'_> {
| ------------------------- ^^ expected named lifetime parameter
|
= help: this function's return type contains a borrowed value, but the signature does not say which one of `items`'s 3 lifetimes it is borrowed from
help: consider introducing a named lifetime parameter
|
18 | fn new<'a>(items: &'a Vec<(&str, &str, usize)>) -> App<'a> {
| ++++ ++ ~~
但是,在这里 with_items
方法我可以愉快地终身:
struct StatefulList<'a, T> {
state: ListState,
items: &'a Vec<T>,
}
impl<T> StatefulList<'_, T> {
fn with_items(items: &Vec<T>) -> StatefulList<'_, T> {
StatefulList {
state: ListState::default(),
items,
}
}
}
为什么?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
编译器告诉您原因:
从类型
三个寿命>&amp; vec&lt;(&amp; str,str,usize)&gt; :
&amp; /代码>。 lifetime Elision sulision ulision规则只能在返回类型时选择寿命有一个一个参数,或者如果有
self
参数,则在这种情况下它们使用其寿命。The compiler is telling you why:
There are three lifetimes in the type
&Vec<(&str, &str, usize)>
:&'a Vec<(&'b str, &'c str, usize)>
. The lifetime elision rules can only choose the lifetime for the return type when there is one parameter, or if there is aself
parameter in which case they uses its lifetime.