fmt::Debug
难以看起来紧凑和清洁,因此它通常是有利的定制的输出的外观。 这是通过 fmt::Display
使用 {}
打印标记手动执行完成。实现它看起来像这样:
// Import (via `use`) the `fmt` module to make it available. |
use std::fmt; |
// Define a structure which `fmt::Display` will be implemented for. This is simply |
// a tuple struct containing an `i32` bound to the name `Structure`. |
struct Structure(i32); |
// In order to use the `{}` marker, the trait `fmt::Display` must be implemented |
// manually for the type. |
impl fmt::Display for Structure { |
// This trait requires `fmt` with this exact signature. |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
// Write strictly the first element into the supplied output |
// stream: `f`. Returns `fmt::Result` which indicates whether the |
// operation succeeded or failed. Note that `write!` uses syntax which |
// is very similar to `println!`. |
write!(f, "{}", self.0) |
} |
} |
fmt::Display
可以比 fmt::Debug
更干净,但是这给 std
库带来的一个问题。 应该如何将不明确类型显示?例如,如果 std
库为所有Vec<T>
实现一个单一的风格,那么它应该是什么风格?这两种还是一种?
Vec<path>
: /:/etc:/home/username:/bin
(使用 :
分隔)
Vec<number>
: 1,2,3
(使用 :
分隔)
没有,因为没有理想的风格为所有类型使用,std 库并不自己支配。fmt::Display 没有为Vec<T>或任何其它通用的容器实现。 fmt::Debug 必须用这些通用类型。
因为任何新的容器类型的一个问题是不能通用, 但 fmt::Display 可以实现。