首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >生命周期必须对静态生命周期有效

生命周期必须对静态生命周期有效
EN

Stack Overflow用户
提问于 2019-11-11 18:40:48
回答 1查看 485关注 0票数 1
代码语言:javascript
复制
trait X {}

trait Y {}

struct A {}

impl X for A {}

struct B<'r> {
    x: &'r mut Box<dyn X + 'r>,
    id: i32,
}

impl <'r> Y for B<'r> {}


struct Out {
    x: Box<dyn X>,
}

impl Out {
    pub fn new() -> Self {
        return Out {
            x: Box::new(A{})
        }
    }

    pub fn get_data(&mut self) -> Box<dyn Y> {
        return Box::new(B{
            id: 1,
            x: &mut self.x
        })
    }
}

在操场上运行它的here

我从编译器那里得到了这条信息:

代码语言:javascript
复制
note: but, the lifetime must be valid for the static lifetime...
   = note: ...so that the expression is assignable:
           expected &mut std::boxed::Box<dyn X>
              found &mut std::boxed::Box<(dyn X + 'static)>

我知道静态生命周期是从哪里来的,但是在结构B的创建过程中不会传递相同的生命周期给它,因为它接受任何泛型生命周期。

在以下答案后编辑

我也尝试过将struct设为泛型,但在初始化后无法使用它。

EN

回答 1

Stack Overflow用户

发布于 2019-11-11 19:21:48

我修复了它(playground)。相关代码如下:

代码语言:javascript
复制
// note the lifetime!
struct Out<'a> {
    x: Box<dyn X + 'a>,
}

// note the lifetime!
impl<'a> Out<'a> {
    pub fn new() -> Self {
        return Out {
            x: Box::new(A{})
        }
    }

    pub fn get_data(&'a mut self) -> Box<dyn Y + 'a> {
        return Box::new(B {
            id: 1,
            x: &mut self.x,
        })
    }
}

为什么需要这样做?

特征对象总是有一个生命周期。如果未指定或推断生存期,则默认为'static。因此,您必须使Out在其生命周期内成为泛型,并在实现中使用它。

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

https://stackoverflow.com/questions/58799788

复制
相关文章

相似问题

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