Rust 格式/Formatting
我们已经看到,通过指定的格式格式字符串:
-
format!("{}", foo)
%uA0->%uA0"3735928559"
-
format!("0x{:X}", foo)
%uA0->%uA0"0xDEADBEEF"
-
format!("0o{:o}", foo)
%uA0->%uA0"0o33653337357"
相同的变量(foo)可以格式化成不同形式,具体取决于使用哪个参数类型:%uA0X
%uA0vso
%uA0和%uA0unspecified.
这种格式化功能是通过特征来实现,并且每一个参数的类型有各个特征。最常见的格式特征是%uA0Display
,%uA0它处理参数类型的未指定情况,例如:%uA0{}
%uA0
use std::fmt::{self, Formatter, Display} struct City { name: &&aposstatic str, // Latitude lat: f32, // Longitude lon: f32, } impl Display for City { // `f` is a buffer, this method must write the formatted string into it fn fmt(&self, f: &mut Formatter) -> fmt::Result { let lat_c = if self.lat >= 0.0 { &aposN&apos } else { &aposS&apos } let lon_c = if self.lon >= 0.0 { &aposE&apos } else { &aposW&apos } // `write!` is like `format!`, but it will write the formatted string // into a buffer (the first argument) write!(f, "{}: {:.3}%uB0{} {:.3}%uB0{}", self.name, self.lat.abs(), lat_c, self.lon.abs(), lon_c) } } fn main() { for city in [ City { name: "Dublin", lat: 53.347778, lon: -6.259722 }, City { name: "Oslo", lat: 59.95, lon: 10.75 }, City { name: "Vancouver", lat: 49.25, lon: -123.1 }, ].iter() { println!("{}", *city) } }
下面是格式化特征和它们各自的参数类型的完整列表:
-
unspecified%uA0->%uA0
Display
-
?
%uA0->%uA0Debug
-
o
%uA0->%uA0Octal
-
x
%uA0->%uA0LowerHex
-
X
%uA0->%uA0UpperHex
-
p
%uA0->%uA0Pointer
-
b
%uA0->%uA0Binary
-
e
%uA0->%uA0LowerExp
-
E
%uA0->%uA0UpperExp