简体   繁体   English

返回向量中特征的可变引用

[英]Returning mutable reference of trait in vector

New to rust, I'm trying to build a state stack. rust 的新手,我正在尝试构建一个 state 堆栈。

pub trait State {
    fn tick(&mut self);
}

pub struct StateStack {
    stack: Vec<Box<dyn State>>,
}

impl StateStack {
    pub fn push(&mut self, state: Box<dyn State>) {
        self.stack.push(state);
    }

    pub fn current(&mut self) -> &mut dyn State
    {
        &**self.stack.last_mut().expect("No state in stack")
    }
}

When compiling, I get this error:编译时,我收到此错误:

error[E0308]: mismatched types
  --> src/main.rs:16:9
   |
14 |     pub fn current(&mut self) -> &mut dyn State
   |                                  -------------- expected `&mut dyn State` because of return type
15 |     {
16 |         &**self.stack.last_mut().expect("No state in stack")
   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ types differ in mutability
   |
   = note: expected mutable reference `&mut dyn State`
                      found reference `&(dyn State + 'static)`

I don't understand where this State + 'static' come from, is this even the issue?我不明白这个State + 'static'来自哪里,这甚至是问题所在吗? I'm not sure where to begin to analyze this error.我不确定从哪里开始分析这个错误。 I think I get the deref chain right, but I feel I might be missing something here.我想我得到了正确的deref 链,但我觉得我可能在这里遗漏了一些东西。

As a side question, I'm an OOP developper, and I'm not sure that what I'm doing is going the rustly way.作为附带问题,我是 OOP 开发人员,我不确定我正在做的事情是否会生锈。 Any other architecture to considere for state stack? state 堆栈还有其他架构要考虑吗?

The issue is you downgrade the mutable reference you got with last_mut to an immutable reference when you use &** .问题是您在使用&**时将通过last_mut获得的可变引用降级为不可变引用。 You need to instead take a mutable reference and that will solve the issue:您需要取而代之的是可变引用,这将解决问题:

 &mut **self.stack.last_mut().expect("No state in stack")

As for &(dyn State + 'static') , you can mostly just ignore the 'static .至于&(dyn State + 'static') ,您基本上可以忽略'static Anonymous traits ( dyn Trait ) are not concrete types so they may not all share the same lifetime requirements.匿名特征 ( dyn Trait ) 不是具体类型,因此它们可能不会都具有相同的生命周期要求。 dyn State + 'static indicates an anonymous State trait which can survive for a lifetime of 'static . dyn State + 'static表示一个匿名的State trait 可以在'static的一生中存活。 'static just means that a lifetime in unconstrained and could be placed in a static context. 'static只是意味着生命周期不受约束,可以放在 static 上下文中。 Most types have a lifetime of 'static so it does not get included in regular use.大多数类型的生命周期为'static ,因此它不会包含在常规使用中。 Some types with 'static lifetimes would be primitives like u32 or f64 .某些具有'static生命周期的类型将是原语,例如f64 u32 Any dyn Trait which does not include a lifetime gets an implicit 'static .任何不包含生命周期的dyn Trait都会得到一个隐式'static

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM