如何为trait实现指定引用生存期



如何为struct Foo实现TraitFoo ?

#[derive(Debug)]
struct Foo<'f> {
    os: Option<&'f str>
}
impl<'f> Foo<'f> {
    fn new(x: &'f str) -> Foo<'f> {
        Foo {
            os:Some(x)
        }       
    }
}
trait TraitFoo {
    fn foo(x:&str) -> Self;
}
impl<'f> TraitFoo for Foo<'f> {
    fn foo(x: &str) -> Foo<'f> {
        Foo {
            os:Some(x)
        }
    }
}
fn main() {
    println!("{:?}", Foo::new("one"));
    println!("{:?}", Foo::foo("two"));
}

上面的代码出错:

lf_trait.rs:21:12: 21:13 error: cannot infer an appropriate lifetime for automatic coercion due to conflicting requirements
lf_trait.rs:21          os:Some(x)
lf_trait.rs:19:2: 23:3 help: consider using an explicit lifetime parameter as shown: fn foo(x: &'f str) -> Foo<'f>
lf_trait.rs:19  fn foo(x:&str) -> Foo<'f> {
lf_trait.rs:20      Foo{
lf_trait.rs:21          os:Some(x)
lf_trait.rs:22      }
lf_trait.rs:23  }

在函数fn foo(x:&'f str) -> Foo<'f>中使用生存期'f会产生其他错误:

lf_trait.rs:19:2: 23:3 error: method `foo` has an incompatible type for trait: expected bound lifetime parameter , found concrete lifetime [E0053]
lf_trait.rs:19  fn foo(x:&'f str) -> Foo<'f> {
lf_trait.rs:20      Foo{
lf_trait.rs:21          os:Some(x)
lf_trait.rs:22      }
lf_trait.rs:23  }

是否有办法实现TraitFooFoo ?


目的:

我尝试创建自己的错误类,指定错误出现的位置。我需要类似的特性来将标准错误转换为我的错误:

pub trait FromWhere<'a,T>:std::convert::From<T> {
    fn from_where(T, &'a str) -> Self;
}
impl<'e,T:ApplyWrpErrorTrait+std::convert::From<T>+'static> FromWhere<'e,T> for WrpError<'e> {
  fn from_where(err: T, whr:&'e str) -> WrpError<'e> {
      if whr!="" {
          WrpError{
              kind: ErrorKind::Wrapped,
              descr: None,
              pos: Some(whr),
              cause: Some(Box::new(err))
          }
      }else{
          std::convert::From::from(err)
      }
  }
}

您还需要指定trait的生存期。

trait TraitFoo<'a> {
    fn foo(x: &'a str) -> Self;
}
impl<'a> TraitFoo<'a> for Foo<'a> {
    fn foo(x:&'a str) -> Foo<'a> {
        Foo{
            os:Some(x)
        }
    }
}

最新更新