Rust by Example | страница 8
>// `write!` is like `format!`, but it will write the formatted string
>// into a buffer (the first argument)
>write!(f, "{}: {:.3}°{} {:.3}°{}",
>self.name, self.lat.abs(), lat_c, self.lon.abs(), lon_c)
>}
>}
>#[derive(Debug)]
>struct Color {
>red: u8,
>green: u8,
>blue: u8,
>}
>fn main() {
>for city in [
>City { name: "Dublin", lat: 53.347778, lon: -6.259722 },
>City { name: "Oslo", lat: 59.95, lon: 10.75 },
>City { name: "Vancouver", lat: 49.25, lon: -123.1 },
>].iter() {
>println!("{}", *city);
>}
>for color in [
>Color { red: 128, green: 255, blue: 90 },
>Color { red: 0, green: 3, blue: 254 },
>Color { red: 0, green: 0, blue: 0 },
>].iter() {
>// Switch this to use {} once you've added an implementation
>// for fmt::Display.
>println!("{:?}", *color);
>}
>}
>הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה
>XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
You can view a full list of formatting traits and their argument types in the std::fmt documentation.
Add an implementation of the fmt::Display trait for the Color struct above so that the output displays as:
>RGB (128, 255, 90) 0x80FF5A
>RGB (0, 3, 254) 0x0003FE
>RGB (0, 0, 0) 0x000000
Two hints if you get stuck:
• You may need to list each color more than once,
• You can pad with zeros to a width of 2 with :02.
Rust provides access to a wide variety of primitives. A sample includes:
• signed integers: i8, i16, i32, i64, i128 and isize (pointer size)
• unsigned integers: u8, u16, u32, u64, u128 and usize (pointer size)
• floating point: f32, f64
• char Unicode scalar values like 'a', 'α' and '∞' (4 bytes each)
• bool either true or false
• and the unit type (), whose only possible value is an empty tuple: ()
Despite the value of a unit type being a tuple, it is not considered a compound type because it does not contain multiple values.
• arrays like [1, 2, 3]
• tuples like (1, true)
Variables can always be type annotated. Numbers may additionally be annotated via a suffix