乘法时移动值

Moved values when multiplying numbers

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

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,怎么了?

prod.mul 是来自 Mul 特征的乘法方法,它有两个值(两个操作数)和 returns 另一个值(结果)。在本例中,它按值获取 prod,因此 prod 被消耗,移至方法调用中。

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