Rust 方法体的生存期不超过impl的生存期

Rust 方法体的生存期不超过impl的生存期,rust,Rust,我试图实现一个特性,通过enumVariant将函数应用于struct的所有字段,希望它在编译时总是内联的。 可悲的是,我根本无法计算出生命的长度。以下代码返回: pub enum Variant<'a> { Str(&'a str), Int(usize) } impl<'a> From<&'a str> for Variant<'a> { fn from(value: &'a str) -> Self {

我试图实现一个特性,通过enum
Variant
将函数应用于struct的所有字段,希望它在编译时总是内联的。 可悲的是,我根本无法计算出生命的长度。以下代码返回:

pub enum Variant<'a> { Str(&'a str), Int(usize) }

impl<'a> From<&'a str> for Variant<'a> {
    fn from(value: &'a str) -> Self {
        Variant::Str(value)
    }
}

pub struct Foo<T> { foo: T }

pub trait Foreach {
    fn foreach(&self, fun: impl FnMut(&Variant));
}


impl<'a,T:'a> Foreach for Foo<T> where &'a T: Into<Variant<'a>>{
    fn foreach(&'a self, fun: impl FnMut(&Variant<'a>)) {
        fun("Foo: ".into());
        fun(&(&self.foo).into()); // The variant should never escape this scope. The function should consume it immediately.
    }
}
变量自身的发布枚举变量{
变量::Str(值)
}
}
pub结构Foo{Foo:T}
酒馆{
fn foreach(&self,fun:impl-FnMut(&Variant));
}
将Foo的impl Foreach where&'at:转换为src/lib.rs:17:5
|
17 |/fn foreach(&'a self,fun:impl-FnMut(&Variant-src/lib.rs:16:6
|
16 |不满足&'a T:Into:std::convert::From`的Foo的impl Foreach
-->src/lib.rs:18:13
|
18 |乐趣(“Foo:.into());
|^^^^^^^^^^^^^^^^^^特性“std::convert::From”未针对“&Variant as std::convert::From”实现,但未针对“&str”实现`

我认为你可以通过使用更高的等级特征界限来解决这个问题,这是有文档记录的

从文件中:


因为我在看了10秒钟的问题后倾向于链接到更高级别的trait bounds doc。@idursun非常感谢。你想正式回答它吗?这回答了你的问题吗?其他与HRTBs有关的问题:,和。在处理操作符重载时,它也会出现很多问题,例如@FordO.post我没有回答。@Martencacher我添加了链接文档的摘录。
error[E0308]: method not compatible with trait
  --> src/lib.rs:17:5
   |
17 |     fn foreach(&'a self, fun: impl FnMut(&Variant<'a>)) {
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ lifetime mismatch
   |
   = note: expected fn pointer `fn(&Foo<T>, _)`
              found fn pointer `fn(&'a Foo<T>, _)`
note: the anonymous lifetime #1 defined on the method body at 17:5...
  --> src/lib.rs:17:5
   |
17 | /     fn foreach(&'a self, fun: impl FnMut(&Variant<'a>)) {
18 | |         fun("Foo: ".into());
19 | |         fun(&(&self.foo).into()); // The variant should never escape this scope. The function should consume it immediately.
20 | |     }
   | |_____^
note: ...does not necessarily outlive the lifetime `'a` as defined on the impl at 16:6
  --> src/lib.rs:16:6
   |
16 | impl<'a,T:'a> Foreach for Foo<T> where &'a T: Into<Variant<'a>>{
   |      ^^

error[E0277]: the trait bound `&Variant<'_>: std::convert::From<&str>` is not satisfied
  --> src/lib.rs:18:13
   |
18 |         fun("Foo: ".into());
   |             ^^^^^^^^^^^^^^ the trait `std::convert::From<&str>` is not implemented for `&Variant<'_>`
   |
   = help: the following implementations were found:
             <Variant<'a> as std::convert::From<&'a str>>
   = note: `std::convert::From<&str>` is implemented for `&mut Variant<'_>`, but not for `&Variant<'_>`
   = note: required because of the requirements on the impl of `std::convert::Into<&Variant<'_>>` for `&str`