Rust HRTB:由包含生存期类型参数的特征限定的具体类型vs仅由生存期类型参数限定的具体类型

Rust HRTB:由包含生存期类型参数的特征限定的具体类型vs仅由生存期类型参数限定的具体类型,rust,traits,lifetime,Rust,Traits,Lifetime,这实际上是这个问题的一个重要方面 考虑以下代码: 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(); } 现在,我的直觉是,hrtb表达式的翻转以for开头,

这实际上是这个问题的一个重要方面

考虑以下代码:

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();
}

现在,我的直觉是,hrtb表达式的翻转以
for
开头,表示T的生存期必须满足所有可能的生存期——实际上意味着它必须是静态的,因此d也必须有静态的生存期。不过,这里应该没有必要使用hrtb,对吧?是的,这是因为我们只是在玩弄相关的问题。
fn test<T>(t: T)
where
    T: for<'s> Trait<'s>,
{
    t.func();
}
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