ozanmuyes
ozanmuyes

Reputation: 806

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;

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)

Upvotes: 7

Views: 2253

Answers (1)

ozanmuyes
ozanmuyes

Reputation: 806

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 (thanks to @kmdreko).

Upvotes: 7

Related Questions