格式化
我们已经看到,格式化是通过一个_格式字符串_来指定的:
format!("{}", foo)
->"3735928559"
format!("0x{:X}", foo)
->"0xDEADBEEF"
format!("0o{:o}", foo)
->"0o33653337357"
同一个变量(foo
)可以根据使用的参数类型而有不同的格式化方式:X
、o
或未指定。
这种格式化功能是通过 trait 实现的,每种参数类型都对应一个 trait。最常用的格式化 trait 是 Display
,它处理参数类型未指定的情况,例如 {}
。
你可以在 std::fmt
文档中查看格式化 trait 的完整列表及其参数类型。
练习
为上面的 Color
结构体实现 fmt::Display
trait,使输出显示如下:
RGB (128, 255, 90) 0x80FF5A
RGB (0, 3, 254) 0x0003FE
RGB (0, 0, 0) 0x000000
Two hints if you get stuck:
- 你可能需要多次列出每种颜色。
- You can pad with zeros to a width of 2 with
:0>2
. For hexadecimals, you can use:02X
.
Bonus:
- If you would like to experiment with type casting in advance, the formula for calculating a color in the RGB color space is
RGB = (R * 65_536) + (G * 256) + B
, whereR is RED, G is GREEN, and B is BLUE
. An unsigned 8-bit integer (u8
) can only hold numbers up to 255. To castu8
tou32
, you can writevariable_name as u32
.