Last active
February 25, 2019 07:17
-
-
Save jakobii/5f67712b6eeac05b085bb4ad5c1ade35 to your computer and use it in GitHub Desktop.
implement fmt::Display on a struct in Rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| use std::fmt; | |
| // IPv4 struct is just a tuple of u8's. | |
| // just an arbitrary, but realistic example... | |
| struct IPv4(u8, u8, u8, u8); | |
| // declare the impl block for out IPv4 struct. | |
| impl fmt::Display for IPv4 { | |
| // this is the function signature the fmt::distplay trait is looking for. | |
| // https://doc.rust-lang.org/std/fmt/trait.Display.html | |
| fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
| // use write! macro just like println! macro, but output gets writen to | |
| // the formatter struct. | |
| write!(f, "{}.{}.{}.{}", self.0, self.1, self.2, self.3) | |
| } | |
| } | |
| fn main() { | |
| // notice how you simple this struct declaration is. | |
| // very refreshingly easy. | |
| let ipv4 = IPv4(192, 168, 0, 1); | |
| // println macro calls IPv4.fmt() on out ipv4 struct. | |
| // now the plrintln marco knows how to print our struct. | |
| println!("{}", ipv4); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment