rust - 如何为特征实现指定引用生命周期?

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

最佳答案

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

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

关于rust - 如何为特征实现指定引用生命周期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31537018/

相关文章:

rust - 为什么我不能从函数返回 Vec<&str>?

rust - 为什么在我引用的结构上未使用生命周期?

rust - 为什么不能在结构定义中省略生命周期?

rust - 取消引用从 Rust 传递给 C 的类型定义指针时的段错误

rust - 当 Rust FFI 函数返回一个没有#[repr(C)] 的结构给 C 时返回什么?

mysql - 如何将使用 Node Buffers 创建的 MySQL BINARY 列转换为 Rust 中的字符串?

generics - 如何为对特征本身的关联类型的引用编写特征绑定(bind)?

rust - 使用 Tokio 启动多线程

rust - 如何指定在 Rust dylib 中使用哪个 ELF 部分

rust - 从 Actix Web 应用程序中间件访问应用程序状态