受evilone在帖子How to print a Vec?中提供的代碼的啓發。要顯示一個矩陣,我寫的代碼如下:使用for循環顯示矩陣時的不匹配類型
use std::{ops, fmt};
#[derive(PartialEq, Debug)]
pub struct Matrix<T> {
data: Vec<T>,
row: usize,
col: usize,
}
impl<T: Copy> Matrix<T> {
pub fn new(row: usize, col: usize, values: &[T]) -> Matrix<T> {
Matrix {
data: values.to_vec(),
row: row,
col: col,
}
}
}
//// Display
impl<T: fmt::Display> fmt::Display for Matrix<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let n_row = self.row;
let n_col = self.col;
let data = self.data;
for i in 0.. n_row {
let mut each_row = String::new();
for j in 0.. n_col {
let idx = i * n_col + j;
let each_element = data[idx];
each_row.push_str(&each_element.to_string());
each_row.push_str(" "); // seperated by space
}
write!(f, "{}", each_row)
}
}
}
fn main() {
let x = Matrix::new(2, 3, &[-6, -5, 0, 1, 2, 3]);
println!("{}", x);
}
我得到的錯誤:
rustc 1.13.0 (2c6933acc 2016-11-07)
error[E0308]: mismatched types
--> <anon>:40:13
|
40 | write!(f, "{}", each_row)
| ^^^^^^^^^^^^^^^^^^^^^^^^^ expected(), found enum `std::result::Result`
|
= note: expected type `()`
= note: found type `std::result::Result<(), std::fmt::Error>`
= note: this error originates in a macro outside of the current crate
error[E0308]: mismatched types
--> <anon>:31:9
|
31 | for i in 0.. n_row {
| ^expected enum `std::result::Result`, found()
|
= note: expected type `std::result::Result<(), std::fmt::Error>`
= note: found type `()`
1)我不明白爲什麼我得到expected(), found enum `std::result::Result`
2)對於第二錯誤,我認爲這是由於沒有實現第40行而引起的。因此,如果修復第40行,這將不再是問題。
任何建議來解決這個問題?
非常感謝您指導我看到本質。我完全同意我應該學會如何深入瞭解錯誤報告並製作MCVE案例。這些日子裏,我在魯斯特掙扎和學習很多。 – enaJ
@enaJ繼續努力!製作一個重複出現錯誤的簡化案例可以幫助您在整個編程生涯中發揮作用。 – Shepmaster
絕對!我來自蟒蛇背景,6周前開始學習Rust。他們在很多方面都有很大的不同。但我確實認爲每種語言都有助於更深入地瞭解另一種語言。 – enaJ