Fmt

Rust的Fmt核心组成的宏和trait:format!format_arg!print!println!write!;DebugDisplay

  1. fn main() {
  2. let building = format!("{1}有{0:>0width$}米宽,{height:?}米高",
  3. 220, "大厦", width=4, height=666);
  4. print!("{}", building);
  5. }
  • format!:将格式化文本写入String
  • print!:格式相同! 但是文本被打印到控制台(io :: stdout)。
  • println !:和print一样! 但附加换行符。
  • eprint !:格式相同! 但文本打印到标准错误(io :: stderr)。
  • eprintln !:与eprint相同!但附加了换行符。

std :: fmt包含许多控制文本显示的特征。 所有标准库的类型都实现两个重要的基本trait:fmt :: Debugfmt :: Display,对于任何非通用的新类型 都可以自己手动实现fmt::Display:

  • fmt :: Debug:使用{:?}标记。 格式化文本以进行调试,Rust也提供“漂亮打印” {:#?}.
  • fmt :: Display:使用{}标记。 以更优雅,用户友好的方式格式化文本。
  1. use std::fmt; // Import `fmt`
  2. // A structure holding two numbers. `Debug` will be derived so the results can
  3. // be contrasted with `Display`.
  4. #[derive(Debug)]
  5. struct MinMax(i64, i64);
  6. // Implement `Display` for `MinMax`.
  7. impl fmt::Display for MinMax {
  8. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  9. // Use `self.number` to refer to each positional data point.
  10. write!(f, "({}, {})", self.0, self.1)
  11. }
  12. }
  13. // Define a structure where the fields are nameable for comparison.
  14. #[derive(Debug)]
  15. struct Point2D {
  16. x: f64,
  17. y: f64,
  18. }
  19. // Similarly, implement for Point2D
  20. impl fmt::Display for Point2D {
  21. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  22. // Customize so only `x` and `y` are denoted.
  23. write!(f, "x: {}, y: {}", self.x, self.y)
  24. }
  25. }
  26. fn main() {
  27. let minmax = MinMax(0, 14);
  28. println!("Compare structures:");
  29. println!("Display: {}", minmax);
  30. println!("Debug: {:?}", minmax);
  31. let big_range = MinMax(-300, 300);
  32. let small_range = MinMax(-3, 3);
  33. println!("The big range is {big} and the small is {small}",
  34. small = small_range,
  35. big = big_range);
  36. let point = Point2D { x: 3.3, y: 7.2 };
  37. println!("Compare points:");
  38. println!("Display: {}", point);
  39. println!("Debug: {:?}", point);
  40. // Error. Both `Debug` and `Display` were implemented but `{:b}`
  41. // requires `fmt::Binary` to be implemented. This will not work.
  42. // println!("What does Point2D look like in binary: {:b}?", point);
  43. }

格式化

format!宏调用的时候参数可以是任意类型,可以position参数和key-value参数混合使用的。但是key-value的值只能出现在position值之后并且不占position。关于参数规则就是,参数类型必须要实现 std::fmt mod 下的某些trait。比如我们看到原生类型大部分都实现了DisplayDebug这两个宏,其中整数类型还会额外实现一个Binary,等等。可以通过 {:type}的方式去调用这些参数。type这个地方为空的话默认调用的是Display这个trait。

  1. format!("{:b}", 2);
  2. // 调用 `Binary` trait
  3. // Get : 10
  4. format!("{:?}", "Hello");
  5. // 调用 `Debug`
  6. // Get : "Hello"

从上面的{0:>0width$}来分析,首先>是一个语义,它表示的是生成的字符串向右对齐。与之相对的还有<(向左对齐)和^(居中)。再接下来0是一种特殊的填充语法,他表示用0补齐数字的空位,要注意的是,当0作用于负数的时候,

在width和type之间会有一个叫精度的区域(可以省略不写),他们的表示通常是以.开始的,比如.4表示小数点后四位精度。最让人遭心的是,你仍然可以在这个位置引用参数,只需要和上面width一样,用.N$来表示一个position的参数,但是就是不能引用key-value类型的。这一位有一个特殊用法,那就是.*,它不表示一个值,而是表示两个值!第一个值表示精确的位数,第二个值表示这个值本身。这是一种很尴尬的用法,而且极度容易匹配到其他参数。因此,我建议在各位能力或者时间不欠缺的时候尽量把格式化表达式用标准的形式写的清楚明白。尤其在面对一个复杂的格式化字符串的时候。

  1. format_string := <text> [ maybe-format <text> ] *
  2. maybe-format := '{' '{' | '}' '}' | <format>
  3. format := '{' [ argument ] [ ':' format_spec ] '}'
  4. argument := integer | identifier
  5. format_spec := [[fill]align][sign]['#']['0'][width]['.' precision][type]
  6. fill := character
  7. align := '<' | '^' | '>'
  8. sign := '+' | '-'
  9. width := count
  10. precision := count | '*'
  11. type := identifier | '?' | ''
  12. count := parameter | integer
  13. parameter := argument '$'