Rust格式化
Rust 格式/Formatting
我們已經看到,通過指定的格式格式字符串:
-
format!("{}", foo)
->"3735928559"
-
format!("0x{:X}", foo)
->"0xDEADBEEF"
-
format!("0o{:o}", foo)
->"0o33653337357"
相同的變量(foo)可以格式化成不同形式,具體取決於使用哪個參數類型: X
vso
和 unspecified.
這種格式化功能是通過特徵來實現,並且每一個參數的類型有各個特徵。最常見的格式特徵是 Display
, 它處理參數類型的未指定情況,例如: {}
use std::fmt::{self, Formatter, Display};
struct City {
name: &'static 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 { 'N' } else { 'S' };
let lon_c = if self.lon >= 0.0 { 'E' } else { 'W' };
// \`write!\` is like \`format!\`, but it will write the formatted string
// into a buffer (the first argument)
write!(f, "{}: {:.3}°{} {:.3}°{}",
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 ->
Display
-
?
->Debug
-
o
->Octal
-
x
->LowerHex
-
X
->UpperHex
-
p
->Pointer
-
b
->Binary
-
e
->LowerExp
-
E
->UpperExp