我有一个结构:
use std::fmt;
struct SomeStruct {
e1: i32,
e2: f64,
}
impl fmt::Display for SomeStruct {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({}, {})", self.e1, self.e2)
}
}
fn printstuff(name: &str, slc: &[SomeStruct]) {
println!("{} is {}", name, slc);
}
fn main() {
let cap = [
SomeStruct { e1: 1, e2: 1.1 },
SomeStruct { e1: 2, e2: 2.2 },
SomeStruct { e1: 3, e2: 3.3 },
SomeStruct { e1: 4, e2: 4.4 },
];
for elem in &cap {
println!(" {}", elem);
}
println!("cap[1]={}", cap[1]);
println!("cap[2]={}", cap[2]);
printstuff("cap", cap);
}
我已经实现了fmt::Display
,但是当我尝试打印SomeStruct
的切片或数组时,出现编译错误:
error[E0277]: `[SomeStruct]` doesn't implement `std::fmt::Display`
--> src/main.rs:15:32
|
15 | println!("{} is {}", name, slc);
| ^^^ `[SomeStruct]` cannot be formatted with the default formatter
|
= help: the trait `std::fmt::Display` is not implemented for `[SomeStruct]`
= note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
= note: required because of the requirements on the impl of `std::fmt::Display` for `&[SomeStruct]`
= note: required by `std::fmt::Display::fmt`
这很有意义-我没有为Display
实现[SomeStruct]
。我该怎么做呢?我找不到任何Rust文档或任何其他能表明我该怎么做的东西。