Created
November 20, 2023 23:32
-
-
Save jasonsalas/0413fb706e3ac7f0f5f8c3fbf34c47a7 to your computer and use it in GitHub Desktop.
Implementing printable enums 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
/* | |
Sports player profiles in Rust 1.73.0 | |
-------------------------------------- | |
This code demo highlights how to: | |
- implement the fmt::Display trait for enums (Line 21) | |
- develop a helper method to capitalize the first letter of words (Line 56) | |
- apply turbofish type casting (Line 60) | |
*/ | |
use std::fmt; | |
#[derive(Debug)] | |
#[allow(dead_code, unused)] | |
enum Position { | |
S, | |
OH, | |
MB, | |
O, | |
L, | |
} | |
impl fmt::Display for Position { | |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
let printable = match *self { | |
Position::S => "Setter", | |
Position::OH => "Outside Hitter", | |
Position::MB => "Middle Blocker", | |
Position::O => "Opposite", | |
Position::L => "Libero", | |
}; | |
write!(f, "{}", printable) | |
} | |
} | |
#[derive(Debug)] | |
#[allow(dead_code, unused)] | |
struct PlayerProfile<'a> { | |
first_name: &'a str, | |
last_name: &'a str, | |
jersey_number: u8, | |
position: Position, | |
} | |
impl fmt::Display for PlayerProfile<'_> { | |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
writeln!( | |
f, | |
"{}, {} ({}) -- #{}", | |
&self.last_name.to_uppercase(), | |
capitalize_first_letter(&self.first_name), | |
&self.position, | |
&self.jersey_number, | |
) | |
} | |
} | |
fn capitalize_first_letter(first_name: &str) -> String { | |
let mut letters = first_name.chars(); | |
match letters.next() { | |
None => String::new(), | |
Some(letter) => letter.to_uppercase().collect::<String>() + letters.as_str(), | |
} | |
} | |
fn main() { | |
let player = PlayerProfile { | |
first_name: "micah", | |
last_name: "christenson", | |
jersey_number: 11, | |
position: Position::S, | |
}; | |
println!( | |
"DEBUG VIEW: {:?}\nPRETTY PRINT VIEW: {:#?}\nFORMATTED VIEW: {}", | |
player, player, player | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment