Created
July 18, 2022 07:48
-
-
Save hassaku63/c8f18ea294259bb2fec4bc3bc4849a14 to your computer and use it in GitHub Desktop.
ユーザー定義の構造体をいい感じに print できるように fmt トレイトを実装する
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; | |
struct Circle { | |
radius: u32 | |
} | |
impl Circle { | |
fn diameter(&self) -> u32 { | |
self.radius * 2 | |
} | |
fn small_circle() -> Circle { | |
Circle { radius: 1 } | |
} | |
} | |
impl fmt::Display for Circle { | |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
write!(f, "Cirdle(radius: {})", self.radius) | |
} | |
} | |
fn main() { | |
let c = Circle{radius: 2}; | |
println!("{}, {}", c.radius, c.diameter()); | |
println!("{}", Circle::small_circle()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment