Error: “use of moved value”

大城市里の小女人 提交于 2019-12-14 02:44:58

问题


I'm currently learning Rust, and am toying around with a simple calculator. When refactoring, I ended up with some code like the following:

enum OptionalToken {
    Foo,
    Bar
}

fn next_token() -> OptionalToken {
    // Read input, classify, return
    OptionalToken::Foo
}


trait Stack {
    // ...
    fn dump (mut self);
}

impl Stack for Vec<f64> {
    // ...
    fn dump (mut self) {
        println!("Stack: size={} [", self.len());
        for x in self.iter() {
            println!("   {}", x);
        };
        println!("]");
    }
}

fn main() {
    let mut stack: Vec<f64> = Vec::new();

    loop {
        let tok = next_token();
        match tok {
            OptionalToken::Foo => { stack.dump(); }
            OptionalToken::Bar => { stack.pop(); }
        }
    }
}

The compiler (nightly build) fails with the following error (same error is actually printed twice as I'm doing the same mistake twice):

src/test.rs:38:37: 38:42 error: use of moved value: `stack`
src/test.rs:38             OptionalToken::Foo => { stack.dump(); }
                                                   ^~~~~
src/test.rs:38:37: 38:42 note: `stack` moved here because it has type `collections::vec::Vec<f64>`, which is non-copyable
src/test.rs:38             OptionalToken::Foo => { stack.dump(); }

What am I doing wrong here? What would I have to modify to get code structured like this to work?


回答1:


The function signature fn dump(mut self) (or fn dump(self), it makes no difference and frankly I'm surprised that the mut is permitted in the trait) means that the method takes the Stack by value, i.e. moves it.

There is no reason to take ownership. Make the signature fn dump(&self) to be able to call it without moving.

If "moving" is is all Greek to you, see the Ownership chapter in TRPL.



来源:https://stackoverflow.com/questions/28277230/error-use-of-moved-value

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