Start learning free

LESSON 614 OF 642 · OBJECT-ORIENTED PROGRAMMING

Printing Objects in Rust in Rust

Lesson

TL ; DR:

Implement the Display trait for your type. Then {} in println! prints it.


use std::fmt;

struct Cat {
    name: String,
}

impl fmt::Display for Cat {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Cat named {}", self.name)
    }
}

// println!("{}", tom) prints Cat named Tom


Full lesson:

The {} in println! works for numbers and strings. It doesn't work for your structs. So println!("{}", tom) doesn't compile. The compiler says that Cat doesn't implement Display.

Display is the trait behind {}. Implement it for your type, as you implemented traits before.

The trait has one method, fmt. It gets &self and f, a Formatter that collects the text. It returns a Result, which says whether writing worked.

Inside, write! puts the text into f. It takes the same {} placeholders as println!. Leave off its semicolon, so its result is what fmt returns.

Once Display is there, format!("{}", tom) and tom.to_string() work too.


Your task

The Dog struct below has a name and an age. Implement Display for it.

Its fmt writes the name, then " is ", the age and " years old". The code in main_function prints two dogs.

Expected output:

Rex is 3 years old
Bella is 5 years old
STEP 1 OF 3
    Ctrl + Enter to check

    Printing Objects in Rust

    Keep going with Rust500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free