预期参考,找到struct

时间:2017-08-29 16:31:50

标签: rust

我试图通过翻译"编程元素"中的C ++代码来学习Rust。 Stepanov和McJones的书。这是一个简单的代码段:

extern crate num_bigint;

use num_bigint::BigInt;

pub fn fibonacci_matrix_multiply(x: (&BigInt, &BigInt), y: (&BigInt, &BigInt)) -> (BigInt, BigInt) {
    (x.0 * (y.1 + y.0) + x.1 * y.0, x.0 * y.0 + x.1 * y.1)
}

pub fn power_accumulate_positive(
    mut r: (&BigInt, &BigInt),
    mut a: (&BigInt, &BigInt),
    mut n: i32,
) -> (BigInt, BigInt) {
    loop {
        if n & 1 == 1 {
            r = fibonacci_matrix_multiply(r, a);
            if n == 1 {
                return r;
            }
        }
        a = fibonacci_matrix_multiply(a, a);
        n = n / 2;
    }
}

fn main() {}

这是错误消息:

error[E0308]: mismatched types
  --> src/main.rs:16:17
   |
16 |             r = fibonacci_matrix_multiply(r, a);
   |                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected reference, found struct `num_bigint::BigInt`
   |
   = note: expected type `(&num_bigint::BigInt, &num_bigint::BigInt)`
              found type `(num_bigint::BigInt, num_bigint::BigInt)`

error[E0308]: mismatched types
  --> src/main.rs:18:24
   |
18 |                 return r;
   |                        ^ expected struct `num_bigint::BigInt`, found reference
   |
   = note: expected type `(num_bigint::BigInt, num_bigint::BigInt)`
              found type `(&num_bigint::BigInt, &num_bigint::BigInt)`

error[E0308]: mismatched types
  --> src/main.rs:21:13
   |
21 |         a = fibonacci_matrix_multiply(a, a);
   |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected reference, found struct `num_bigint::BigInt`
   |
   = note: expected type `(&num_bigint::BigInt, &num_bigint::BigInt)`
              found type `(num_bigint::BigInt, num_bigint::BigInt)`

我知道我会返回一个结构元组,并尝试将其分配给引用元组,但我不知道如何解决问题。

1 个答案:

答案 0 :(得分:4)

是否有理由不按价值而不是按参考取BigInt s?这将删除所有借用检查器错误。除非克隆BigInt是明确且测量的瓶颈,否则通过引用传递的速度会快得多,而且它的人体工程学也不会那样。

这是一个不使用引用的工作解决方案(而是克隆值)

extern crate num_bigint;

use num_bigint::BigInt;

pub fn fibonacci_matrix_multiply(x: (BigInt, BigInt), y: (BigInt, BigInt)) -> (BigInt, BigInt) {
    (&x.0 * (&y.1 + &y.0) + &x.1 * &y.0, x.0 * y.0 + x.1 * y.1)
}

pub fn power_accumulate_positive(
    mut r: (BigInt, BigInt),
    mut a: (BigInt, BigInt),
    mut n: i32,
) -> (BigInt, BigInt) {
    loop {
        if n & 1 == 1 {
            r = fibonacci_matrix_multiply(r, a.clone());
            if n == 1 {
                return r;
            }
        }
        a = fibonacci_matrix_multiply(a.clone(), a);
        n = n / 2;
    }
}