错误:“使用移动值" [英] Error: "use of moved value"

查看:54
本文介绍了错误:“使用移动值"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在学习 Rust,并且正在玩弄一个简单的计算器.重构时,我最终得到了一些如下代码:

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?

推荐答案

函数签名 fn dump(mut self)(或 fn dump(self),它使没有区别,坦率地说,我很惊讶 mut 在 trait 中是允许的)意味着该方法按值获取 Stack,即移动它.

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.

没有理由拥有所有权.使签名 fn dump(&self) 能够调用它而无需移动.

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

如果移动"对您来说完全是希腊语,请参阅所有权TRPL 中的一章.

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

这篇关于错误:“使用移动值"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆