Rust 显示/Display
fmt::Debug
%uA0难以看起来紧凑和清洁,因此它通常是有利的定制的输出的外观。 这是通过%uA0fmt::Display
使用%uA0{}
%uA0打印标记手动执行完成。实现它看起来像这样:
// 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
%uA0可以比%uA0fmt::Debug
%uA0更干净,但是这给%uA0std
%uA0库带来的一个问题。%uA0应该如何将不明确类型显示?例如,如果%uA0std
%uA0库为所有Vec<T>
%uA0
实现一个单一的风格,那么它应该是什么风格?这两种还是一种?
-
Vec<path>
:%uA0/:/etc:/home/username:/bin
%uA0(使用%uA0:
分隔) -
Vec<number>
:%uA01,2,3
%uA0%uA0(使用%uA0:
分隔)
没有,因为没有理想的风格为所有类型使用,std%uA0库并不自己支配。fmt::Display%uA0没有为Vec<T>或任何其它通用的容器实现。%uA0fmt::Debug 必须用这些通用类型。
因为任何新的容器类型的一个问题是不能通用, 但 fmt::Display%uA0可以实现。