【问题标题】:Move a Box inside a Struct在结构内移动一个盒子
【发布时间】:2014-11-20 00:51:47
【问题描述】:

我目前正在玩 Rust,我想实现一种状态设计模式。为此,我需要一个特征框作为结构属性。

让我们想象State 是我的特质。应该是这样的。

pub trait State {
    // some functions
}

pub struct State1 {
    Box<State> s;
}

impl State for State1 {
    // some implementations
}

另一种可能性:

pub struct State2 {
    HashMap<uint, Box<State>> hash;
}

impl State for State2 {
    // some implementations
}

现在,我可以弄清楚如何初始化所有这些。存在终身问题。

我想要的基本上是这样的:

impl State1 {
    pub fn new(s: Box<State1>) {
        State1 {
            s: ... // the value inside Box is moved and now owned
                   // by the new State1 object, so it won't be usable
                   // by the caller after this call and then safe
        }
    }
}

有可能吗?

提前致谢!

【问题讨论】:

    标签: rust ownership


    【解决方案1】:

    你只需要转换成一个 trait 对象

    impl State1 {
        pub fn new(s: Box<State1>) {
            State1 {
                s: s as Box<State>
            }
        }
    }
    

    【讨论】:

    • 哦!这很有趣,我现在正在尝试。但是,我可能犯了一个小错误:不是fn new(s: Box&lt;State1&gt;),而是fn new(s: Box&lt;State&gt;)
    • 哦 :( error: the trait 'controller::object::automate::Automate' is not implemented for the type 'controller::object::automate::Automate'。这是否意味着我需要一个包装器?
    【解决方案2】:
    pub struct AutomateFeeder<'a> {
       automate: Box<Automate + 'a>,
    }
    
    impl<'a> AutomateFeeder<'a> {
        pub fn new<T: Automate + 'a>(automate: Box<T>) -> AutomateFeeder<'a> {
            AutomateFeeder {
                automate: automate as Box<Automate>,
            }
        }
    }
    

    这就是诀窍。

    【讨论】:

      猜你喜欢
      • 2020-10-19
      • 2022-01-17
      • 2019-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多