如何为特征实现指定参考生命周期?

时间:2015-07-21 10:50:50

标签: rust

如何为 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  }

在函数'f中使用生命周期fn foo(x:&'f str) -> Foo<'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  }

有没有办法为TraitFoo实施Foo

关于目的:

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

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

1 个答案:

答案 0 :(得分:0)

您还需要在特征上指定生命周期。

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)
        }
    }
}
相关问题