gpt4 book ai didi

rust - 如何编写 Rust by Example 中的转置函数示例?

转载 作者:行者123 更新时间:2023-11-29 08:33:04 25 4
gpt4 key购买 nike

我正在学习 Rust by Example 教程,并且在 Tuples activity 的第二部分即以reverse函数为模板,添加一个transpose函数。这将接受一个矩阵作为参数并返回一个交换了两个元素的矩阵。例如:

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)
}

最佳答案

使用 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)
}

关于rust - 如何编写 Rust by Example 中的转置函数示例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46221869/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com