简体   繁体   中英

Cannot impl Display for struct in Rust

I've been following along Rust by Example and couldn't achieve debug output of the struct ( Matrix in the code below).

First things first, here are the versions;

  • OS: macOS 11
  • Rust: rustc 1.49.0 (e1884a8e3 2020-12-29)
  • Cargo: cargo 1.49.0 (d00d64df9 2020-12-05)

While I was trying to do what's been asked on the 1st activity of "Activity" section of "Tuples" step;

"Add the fmt::Display trait to the Matrix struct in the above example"

I created a new Rust project via Cargo and created such structure;

$ROOT
├- Cargo.toml
└- src
   ├- main.rs
   └- mytuples2.rs
// src/main.rs

mod mytuples2;

fn main() {
    mytuples2::run();
}

and

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

but unable to produce the following output;

((1.1) (1.2)
 (2.1) (2.2))

What am I doing wrong? Please help me as I'm a newbie. Thanks.

PS: Instead it writes Matrix(1.1, 1.2, 2.1, 2.2)

Despite it's my fault I am going to answer it;

Deleting #[derive(Debug)] before the struct definition and changing impl to impl fmt::Debug for Matrix { (as opposed to impl fmt::Display for Matrix { ) solved it.

No need to change "{:?}" to "{}" as the purpose is to print the struct in the debug format.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM