How to print your Structs the way you want it

How to print your Structs the way you want it

The Struct

Let’s keep it simple here with a struct for a 2D Point in space:

pub struct Point {
    x: i32,
    y: i32
}

 

1st (fail) try

If you try to print an instance of your struct you will get a panicked compiler

let p = Point{x: 10, y: 5};

println!("{}", p);
error[E0277]: `point::Point` doesn't implement `std::fmt::Display`
  --> src/main.rs:22:20
   |
22 |     println!("{}", p);
   |                    ^ `point::Point` cannot be formatted with the default formatter; try using `:?` instead if you are using a format string
   |
   = help: the trait `std::fmt::Display` is not implemented for `point::Point`
   = note: required by `std::fmt::Display::fmt`

As you can see the compiler offered us a couple of hints on how to solve it.

 

Printing with Debug

if you want to simply print your struct “as is” you can add the debug command to your struct and print using the “😕“, like so:

#[derive(Debug)]
pub struct Point {
    x: i32,
    y: i32
}
let p = Point{x: 10, y: 5};

println!("{:?}", p);

and this will yield:

Point { x: 10, y: 5 }

You could also have implemented the Debug trait instead of using the annotation command, however you wouldn’t want to print with “😕” forever right?

 

Implementing the Display trait

Instead of, or even in addition to the step above, you can implement the Display trait and decide how your object should be printed out.

impl Display for Point {
    fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
        write!(f, "p({}, {})", self.x, self.y)
    }
}

Now printing we get our defined structure:

let p = Point{x: 10, y: 5};

println!("{:?}", p);
p(10,5)

 

Leave your opinion, start a discussion, share an experience or just a compliment...

%d bloggers like this: