为什么我需要为不是该结构成员的结构的通用参数提供生命周期? [英] Why do I need to provide lifetimes for a struct's generic parameters which are not members of the struct?
问题描述
我正在努力弄清泛型和生命周期相互作用的方式.考虑:
I'm trying to get my head around the way that generics and lifetimes interact. Consider:
use std::ops::Add;
struct Gloop<'a, T: Add> {
wumpus: &'a Wumpus<T>,
}
trait Wumpus<T: Add> {
fn fleeb(&self, x: &T) -> bool;
}
struct Mimsy {
jubjub: f64,
}
impl<T: Add> Wumpus<T> for Mimsy {
fn fleeb(&self, x: &T) -> bool {
return (x + x) > 0;
}
}
fn main() {
let a = Mimsy { jubjub: 1. };
let b = Gloop::<i32> { wumpus: &a };
println!("{}", b.fleeb(1));
}
哪个产量:
error[E0309]: the parameter type `T` may not live long enough
--> src/main.rs:4:5
|
3 | struct Gloop<'a, T: Add> {
| -- help: consider adding an explicit lifetime bound `T: 'a`...
4 | wumpus: &'a Wumpus<T>,
| ^^^^^^^^^^^^^^^^^^^^^
|
note: ...so that the reference type `&'a Wumpus<T> + 'a` does not outlive the data it points at
--> src/main.rs:4:5
|
4 | wumpus: &'a Wumpus<T>,
| ^^^^^^^^^^^^^^^^^^^^^
程序中的哪个对象可能寿命不长? Gloop
或Mimsy
(或任何Wumpus<T>
)中都没有存储过T
.
Which object in my program is the one which may not live long enough? Nowhere in either Gloop
or Mimsy
(or any Wumpus<T>
) is a T
ever stored.
推荐答案
注意:我回答了这个问题,但认为问题实际上是
Note: I answered this, but think the question is actually a duplicate of
如果其他人同意,可以删除此答案.
This answer can be deleted if others agree.
在
Gloop
或Mimsy
(或任何Wumpus<T>
)中都没有存储过T
.
Nowhere in either
Gloop
orMimsy
(or anyWumpus<T>
) is aT
ever stored.
Rust不在乎您做什么,但在乎您可以做什么.这两种结构之间没有签名差异:
Rust doesn't care about what you do, but what you could do. There are no signature differences between these two structs:
struct Alpha<T> {
a: T,
}
struct Beta<T> {
b: fn(&T),
}
即,您不能说出两者之间的区别,而Beta
可能会变成Alpha
,而无需对消费者进行明显的外部更改.一旦有了通用类型,就需要处理所有可能.
Namely, you can't tell the difference between the two and Beta
could become Alpha
without noticeable external changes to a consumer. Once you have a generic type, you need to handle any possibility.
您可以添加T: 'static
或添加生存期并添加T: 'a
.
You can either add T: 'static
or add a lifetime and add T: 'a
.
另请参阅:
- 为什么终生需要生命
- Why the lifetime is needed at all
- Why is the bound `T: 'a` required in order to store a reference `&'a T`?
- Parameter type may not live long enough?
这篇关于为什么我需要为不是该结构成员的结构的通用参数提供生命周期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- Why the lifetime is needed at all