问题
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