フォーマット
これまで、文字列がどのようにフォーマットされるかは フォーマット文字列 によって決まるということを見てきました 。
format!("{}", foo)
->"3735928559"
format!("0x{:X}", foo)
->"0xDEADBEEF"
format!("0o{:o}", foo)
->"0o33653337357"
ここでは(foo
)という単一の変数がX
、o
、 指定なし 、という様々な 引数タイプ に応じてフォーマットされています。
フォーマットの機能はそれぞれの引数タイプごとに個別のトレイトを用いて実装されています。最も一般的なトレイトはDisplay
で、これは引数タイプが未指定(たとえば{}
)の時に呼び出されます。
フォーマット用トレイトの全リストはこちらから、引数タイプについてはstd::fmt
のドキュメンテーションから参照できます。
演習
上にあるソースコード中のColor
という構造体のためのfmt::Display
トレイトの実装を追加しましょう。出力は以下のようになるはずです。
RGB (128, 255, 90) 0x80FF5A
RGB (0, 3, 254) 0x0003FE
RGB (0, 0, 0) 0x000000
Two hints if you get stuck:
- それぞれの色を2回以上記述する必要があるかもしれません。
- 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
.