【发布时间】:2022-01-22 07:17:30
【问题描述】:
编译器不接受以下代码:
struct Struct<'a, 'b: 'a> {
value: &'a dyn Value<'b>,
}
impl<'a, 'b: 'a> Struct<'a, 'b> {
fn foo(&self) {
UnitedLifetime(self.value);
}
}
struct UnitedLifetime<'a>(&'a dyn Value<'a>);
trait Value<'a> {}
它会产生以下错误:
error[E0495]: cannot infer an appropriate lifetime for automatic coercion due to conflicting requirements
--> src/lib.rs:7:24
|
7 | UnitedLifetime(self.value);
| ^^^^^^^^^^
|
note: first, the lifetime cannot outlive the lifetime `'a` as defined here...
--> src/lib.rs:5:6
|
5 | impl<'a, 'b: 'a> Struct<'a, 'b> {
| ^^
note: ...so that reference does not outlive borrowed content
--> src/lib.rs:7:24
|
7 | UnitedLifetime(self.value);
| ^^^^^^^^^^
note: but, the lifetime must be valid for the lifetime `'b` as defined here...
--> src/lib.rs:5:10
|
5 | impl<'a, 'b: 'a> Struct<'a, 'b> {
| ^^
note: ...so that the types are compatible
--> src/lib.rs:7:24
|
7 | UnitedLifetime(self.value);
| ^^^^^^^^^^
= note: expected `dyn Value<'_>`
found `dyn Value<'b>`
如果我使用 struct Value<'a>(&'a u8); 而不是特征,它会编译。
我想要一个UnitedLifetime,它的生命周期与Struct 一样长,而它又具有其他对象的生命周期,这意味着'a: '_ 和'b: '_ 始终为真。
我做错了什么?这是编译器错误吗?
【问题讨论】:
标签: struct rust traits lifetime coercion