简体   繁体   English

方法体的生命周期不会超过 impl 的生命周期

[英]Lifetime of method body does not outlive lifetime of impl

I tried to implement a trait for applying a function to all fields of struct trough an enum Variant , which should hopefully be always inlined at compilation.我试图通过 enum Variant实现将函数应用于 struct 的所有字段的特征,希望在编译时始终内联。 Sadly I am not able to figure out the lifetimes at all.可悲的是,我根本无法弄清楚寿命。 The following code returns:以下代码返回:

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.
    }
}

Following error:以下错误:

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`

I think you can solve this by using Higher-rank trait bounds which is documented here我认为您可以通过使用此处记录的高级特征边界来解决此问题

From the document:从文件:

for<'a> can be read as "for all choices of 'a", and basically produces an infinite list of trait bounds that F must satisfy. for<'a>可以读作“对于 'a 的所有选择”,并且基本上产生 F 必须满足的无限特征边界列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM