我一直沿Rust by Example跟踪,但无法实现该结构的调试输出(以下代码中的Matrix
)。
首先,这里是版本;
当我尝试执行“Tuples”步骤的"Activity" section的第一项 Activity 时所要求的内容;
"Add the fmt::Display trait to the Matrix struct in the above example"
我通过 cargo 创建了一个新的Rust项目,并创建了这样的结构;
$ROOT
├- Cargo.toml
└- src
├- main.rs
└- mytuples2.rs
// src/main.rs
mod mytuples2;
fn main() {
mytuples2::run();
}
和// src/mytuples2.rs
use std::fmt;
// The following struct is for the activity.
#[derive(Debug)]
struct Matrix(f32, f32, f32, f32);
impl fmt::Display for Matrix {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "(({}) ({})\n ({})({}))", self.0, self.1, self.2, self.3)
}
}
pub fn run() {
let matrix = Matrix(1.1, 1.2, 2.1, 2.2);
println!("{:?}", matrix);
}
但无法产生以下输出;((1.1) (1.2)
(2.1) (2.2))
我究竟做错了什么?我是新手,请帮帮我。谢谢。PS:而是写
Matrix(1.1, 1.2, 2.1, 2.2)
最佳答案
尽管是我的错,我还是要回答。
在结构定义之前删除#[derive(Debug)]
并将impl更改为impl fmt::Debug for Matrix {
(与impl fmt::Display for Matrix {
相对)解决了该问题。
无需将"{:?}"
更改为"{}"
,目的是以调试格式打印结构。
关于rust - 无法在Rust中显示struct的显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65820256/