Implement Display for Item

This is a more idiomatic way of printing the contents of an object
than reaching into its innards. It is also more 1-1 with the original
C# code, which overrides toString for Item.
This commit is contained in:
rrokkam 2020-07-19 13:00:57 -07:00
parent f21ed2ae13
commit c88bdfd53e
2 changed files with 8 additions and 1 deletions

View File

@ -1,3 +1,4 @@
use std::fmt::{self, Display};
pub struct Item {
pub name: String,
pub sell_in: i32,
@ -14,6 +15,12 @@ impl Item {
}
}
impl Display for Item {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}, {}, {}", self.name, self.sell_in, self.quality)
}
}
pub struct GildedRose {
pub items: Vec<Item>,
}

View File

@ -34,7 +34,7 @@ fn main() {
println!("-------- day {} --------", i);
println!("name, sellIn, quality");
for item in &rose.items {
println!("{}, {}, {}", item.name, item.sell_in, item.quality);
println!("{}", item);
}
println!();
rose.update_quality();