在乘以数字时移动值

时间:2015-03-23 04:07:14

标签: rust

我正在尝试使用以下代码:

fn get_max(string:Vec<BigUint>) -> BigUint {
    let mut max:BigUint = num::zero();

    for i in 0..(string.len()-13) {
        let mut prod:BigUint = num::one();
        for j in i..(i+13) {
            prod.mul(&string[j]);
        }

        if prod.clone().gt(&max) {
            max = prod;
        }
    }

    max
}

但是当我尝试编译时出现以下错误:

src/main.rs:13:4: 13:8 error: use of moved value: `prod`
src/main.rs:13          prod.mul(&string[j]);
                        ^~~~
note: `prod` was previously moved here because it has type `num::bigint::BigUint`, which is non-copyable
src/main.rs:16:6: 16:10 error: use of moved value: `prod`
src/main.rs:16      if prod.clone().gt(&max) {
                       ^~~~
src/main.rs:13:4: 13:8 note: `prod` moved here because it has type `num::bigint::BigUint`, which is non-copyable
src/main.rs:13          prod.mul(&string[j]);
                        ^~~~
src/main.rs:17:10: 17:14 error: use of moved value: `prod`
src/main.rs:17          max = prod;
                              ^~~~
src/main.rs:13:4: 13:8 note: `prod` moved here because it has type `num::bigint::BigUint`, which is non-copyable
src/main.rs:13          prod.mul(&string[j]);
                        ^~~~
error: aborting due to 3 previous errors

据我所知,我永远不会移动prod,所以出了什么问题?

1 个答案:

答案 0 :(得分:2)

prod.mul是来自Mul特征的乘法方法,它采用两个值(两个操作数)并返回另一个(结果)。在这种情况下,它按值prod,因此prod被消耗,移入方法调用。

您的意思是prod = prod.mul(&string[j]);,可以使用*运算符更好地编写,而不是调用mul方法:prod = prod * &string[j];(对不起,prod *= &string[j]没有'工作了。)