如何通过示例编写Rust的转置函数示例?

时间:2017-09-14 14:35:12

标签: rust

我按照Rust by Example教程进行操作,并在Tuples activity的第二部分,即使用transpose函数作为模板添加reverse函数。这将接受一个矩阵作为参数并返回一个矩阵,其中两个元素已被交换。例如:

println!("Matrix:\n{}", matrix);
println!("Transpose:\n{}", transpose(matrix));

预期结果:

Input Matrix:
( 1.1 1.2 2.1 2.2 )
Transposed output:
( 1.1 2.1 1.2 2.2 )

我无法找到合适的代码,这是我正在尝试的内容:

// this is defined in the tutorial
#[derive(Debug)]
struct Matrix(f32, f32, f32, f32);

// this is my attempt that does not compile
fn transpose(maat: Matrix) -> (Matrix) {
    let matrix = maat;
    (matrix.0, matrix.2, matrix.1, matrix.3)
}

2 个答案:

答案 0 :(得分:0)

我不想给你完整的解决方案,因为如果你正在学习Rust,我会对你造成伤害。 在本教程的这一点上,您缺少一个关键因素。不是你的错。

Matrix是一个“元组结构”(有时也称为newtype),它在Rust的后续部分中通过示例进行了介绍。 如果你想要向前看,在section on structs你会得到你遗失的两件作品。

第一部分:教程中定义的if (bindingResult.hasErrors()) { return "newEntry";//replace the newentry with the html page that you enter the new entry } 可以用与简单元组类似的方式进行解构。

如果您有struct Matrix(f32, f32, f32, f32);,则可以为其各个元素创建名称:

let matrix = Matrix(1.1, 1.2, 2.1, 2.2);

你做了什么(let Matrix(r1c1, r2c2, r2c1, r2c2) = matrix matrix.0 ...)也有效,但......

第二部分。如果要创建matrix.1的新实例,请执行Matrix。从你试图编写转置你试图返回一个元组,但像Matrix(1.1, 1.2, 2.1, 2.2)这样的元组结构是一个不同的,不兼容的类型(这就是为什么它也被称为“newtype”)

答案 1 :(得分:0)

如示例所示,使用reverse并重写reverse函数以接受f32

fn reverse(pair: (f32, f32)) -> (f32, f32) {
    let (a, b) = pair;
    (b, a)
}

fn transpose(mat: Matrix) -> Matrix {
    let (a, b) = reverse((mat.1, mat.2));
    Matrix(mat.0, a, b, mat.3)
}