这实际上是一个offshoot https://stackoverflow.com/questions/54791718/whats-the-difference-between-a-traits-generic-type-and-a-generic-associated-ty#comment105546315_54803174这个的SO https://stackoverflow.com/questions/54791718/whats-the-difference-between-a-traits-generic-type-and-a-generic-associated-ty问题。
考虑以下代码:
trait Trait<'b> {
fn func(&'b self) {}
}
struct Struct {}
impl<'s> Trait<'s> for Struct {}
fn test<'s, T:'s>(t: T)
where
T: Trait<'s>,
{
t.func();
}
它失败了,因为编译器看到了t
寿命少于's
and 's
由调用者设置(即比堆栈帧长)func
) 并且特征对于类型参数是不变的。但是,如果我在这里引入 HRTB(更高等级特征界限),代码将编译:
fn test<T>(t: T)
where
T: for<'s> Trait<'s>,
{
t.func();
}
现在,特质Trait<'s>
为所有可能的生命周期实施's
代表,因此编译器会选择正确的一个。
但为什么下面的代码会失败呢?
struct Temp<'a> {
x: &'a i32,
}
fn test<T>(t: T)
where
for<'s> T: 's,
{
}
fn main() {
let d = 1i32;
test(Temp { x: &d });
}
它给出了错误:
error[E0597]: `d` does not live long enough
--> src/main.rs:13:20
|
13 | test(Temp { x: &d });
| ---------------^^---
| | |
| | borrowed value does not live long enough
| argument requires that `d` is borrowed for `'static`
14 | }
| - `d` dropped here while still borrowed
这里有什么区别呢?从概念上讲,我发现前面的示例与此示例相同。为什么预期具体类型T
应该仅是/包含参考文献'static
寿命?