2017-09-14 62 views
-1

我遵循Rust by Example教程,並在Tuples activity的第二部分中添加使用reverse函數作爲模板的transpose函數。這將接受一個矩陣作爲參數,並返回一個矩陣,其中兩個元素已被交換。例如:如何通過示例從Rust生成轉置函數示例?

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

爲了加快我們的幫助:你的代碼是什麼輸出/出了什麼問題? – birryree

+0

請查看如何創建[MCVE]。例如,絕大多數'main'函數對你的問題沒有影響。 – Shepmaster

回答

0

我不想給你完整的解決方案,因爲如果你正在學習Rust,我會對你有所幫助。 在本教程的這一點,您缺少一個關鍵因素。不是你的錯。

矩陣是一個「元組結構」(有時也被稱爲newtype),它在後面的例子中被Rust覆蓋。 如果你想偷看,在section on structs你會學到你失蹤的兩件。

第一塊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.0matrix.1 ...)工作過,但...

第二塊。當你想創建一個Matrix的新實例時,你需要做Matrix(1.1, 1.2, 2.1, 2.2)。從你嘗試寫轉置你試圖返回一個元組,但是像一個元組結構像Matrix是一個不同的,不兼容的類型(這就是爲什麼它也被稱爲「新類型」)