Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot impl Display for struct in Rust

Tags:

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)

like image 845
ozanmuyes Avatar asked Aug 03 '26 11:08

ozanmuyes


1 Answers

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).

like image 53
ozanmuyes Avatar answered Aug 06 '26 23:08

ozanmuyes