How to bind multiple fields of a boxed struct without getting “use moved value” error?

我们两清 提交于 2019-11-29 13:59:38
oli_obk

There's some weird interaction with Box going on. You need to add an intermediate let statement that unwraps the box.

List(Some(node)) => {
    let node = *node; // this moves the value from the heap to the stack
    let ListNode { val, tail } = node; // now this works as it should
    List(Some(Box::new(ListNode { val: val, tail: tail.append(value) })))
}

Note that I renamed your function argument to value, so I could write the destructuring in the short form without renaming.

Try it out in the playground.

Non-lexical lifetimes, availing starting in Rust 2018, allows your original code to compile as-is:

struct ListNode<T> {
    val: T,
    tail: List<T>
}

struct List<T>(Option<Box<ListNode<T>>>);

impl<T> List<T> {
    fn append(self, val: T) -> List<T> {
        match self {
            List(None) => List(Some(Box::new(ListNode {
                val: val,
                tail: List(None),
            }))),
            List(Some(node)) => List(Some(Box::new(ListNode {
                val: node.val,
                tail: node.tail.append(val),
            }))),
        }
    }
}

fn main() {}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!