Rust Fundamentals · 25 XP Pro

Implementing Display

println!("{}", x) works for types that implement the standard trait std::fmt::Display. Implementing it teaches your own types to print, and as a bonus gives them to_string() for free.

use std::fmt;

pub struct Version(pub u32, pub u32);

impl fmt::Display for Version {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "v{}.{}", self.0, self.1)
    }
}

// Version(1, 4).to_string() == "v1.4"

The write! macro works like format!, but writes into the formatter and returns a fmt::Result.

Your task

The starter declares two types. Everything must stay pub, because the tests use your crate as lesson. Implement std::fmt::Display for both:

  1. Point { pub x: i32, pub y: i32 } prints as (x, y), for example (3, -4).
  2. Money { pub cents: u64 } prints dollars and two-digit cents with a dollar sign, for example $12.05, $0.99, $3.00.

Sign in to run your code. It's free.