Rust格式化

我们已经看到,通过指定的格式格式字符串:

  • 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
联系我们

邮箱 626512443@qq.com
电话 18611320371(微信)
QQ群 235681453

Copyright © 2015-2022

备案号:京ICP备15003423号-3