首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将struct转换为具有lifetime got的特征“由于要求冲突,无法推断lifetime参数`'a`的适当生存期”

将struct转换为具有lifetime got的特征“由于要求冲突,无法推断lifetime参数`'a`的适当生存期”
EN

Stack Overflow用户
提问于 2018-05-09 15:52:08
回答 1查看 115关注 0票数 1
代码语言:javascript
复制
trait BT {
    fn get_a(&self) -> &A;
}

#[derive(Debug)]
struct A {
    v: i32,
}

impl A {
    fn nb(&self) -> Box<BT> {
        Box::new(B { a: self })
    }
}

#[derive(Debug)]
struct B<'a> {
    a: &'a A,
}

impl<'a> BT for B<'a> {
    fn get_a(&self) -> &A {
        return self.a;
    }
}

fn main() {
    println!("{:?}", A { v: 32 }.nb().get_a());
}

A有一个方法来生成一个引用为AB实例,并且B可能有许多方法访问B.a (A在B中的引用)。如果让A.nb()返回B而不是BT,代码会工作得很好。

我是Rust的新手。这个问题整天都在困扰着我。我该怎么做才能让这段代码工作呢?谢谢!

整个错误报告:

代码语言:javascript
复制
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter `'a` due to conflicting requirements
  --> src\socket\msg\message.rs:53:26
   |
53 |                 Box::new(B{a: self})
   |                          ^
   |
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 52:13...
  --> src\socket\msg\message.rs:52:13
   |
52 | /             fn nb(&self) -> Box<BT> {
53 | |                 Box::new(B{a: self})
54 | |             }
   | |_____________^
note: ...so that reference does not outlive borrowed content
  --> src\socket\msg\message.rs:53:31
   |
53 |                 Box::new(B{a: self})
   |                               ^^^^
   = note: but, the lifetime must be valid for the static lifetime...
   = note: ...so that the expression is assignable:
           expected std::boxed::Box<socket::msg::message::test::test::BT + 'static>
              found std::boxed::Box<socket::msg::message::test::test::BT>
EN

回答 1

Stack Overflow用户

发布于 2018-05-09 18:01:16

特征对象的默认生存期是'static。您需要为nb()函数返回的特征对象添加一个显式的生命周期绑定:

代码语言:javascript
复制
impl A {
    fn nb<'s>(&'s self) -> Box<BT+'s> {
        Box::new(B{a: self})
    }
}

Inference of Trait Object Lifetimes

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50248219

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档