[][src]Function tao_of_rust::ch08::strings::strings_convert

pub fn strings_convert()

字符串和其他类型转换

Base usage: parse转换

fn main() {
    let four: u32 = "4".parse().unwrap();
    assert_eq!(4, four);
    let four = "4".parse::<u32>();
    assert_eq!(Ok(4), four);
}Run

Base usage: 为自定义类型实现FromStr,以便使用parse转换

use std::str::FromStr;
use std::num::ParseIntError;
#[derive(Debug, PartialEq)]
struct Point {
    x: i32,
    y: i32
}
impl FromStr for Point {
    type Err = ParseIntError;
   fn from_str(s: &str) -> Result<Self, Self::Err> {
       let coords = s.trim_matches(|p| p == '{' || p == '}' )
                       .split(",")
                       .collect::<Vec<&str>>();
       let x_fromstr = coords[0].parse::<i32>()?;
       let y_fromstr = coords[1].parse::<i32>()?;
       Ok(Point { x: x_fromstr, y: y_fromstr })
   }
}
fn main(){
   let p = Point::from_str("{1,2}");
   assert_eq!(p.unwrap(), Point{ x: 1, y: 2} );
   let p = Point::from_str("{3,u}");
   //Err(ParseIntError { kind: InvalidDigit })
   println!("{:?}", p);
}Run

Base usage: 其他类型转为字符串

fn main(){
    let s: String = format!("{}Rust", "Hello");
    assert_eq!(s, "HelloRust");
    assert_eq!(format!("{:5}", "HelloRust"), "HelloRust");
    assert_eq!(format!("{:5.3}", "HelloRust"), "Hel  ");
    assert_eq!(format!("{:10}", "HelloRust"), "HelloRust ");
    assert_eq!(format!("{:<12}", "HelloRust"), "HelloRust   ");
    assert_eq!(format!("{:>12}", "HelloRust"), "   HelloRust");
    assert_eq!(format!("{:^12}", "HelloRust"), " HelloRust  ");
   assert_eq!(format!("{:^12.5}", "HelloRust"), "   Hello    ");
   assert_eq!(format!("{:=^12.5}", "HelloRust"), "===Hello====");
   assert_eq!(format!("{:*^12.5}", "HelloRust"), "***Hello****");
   assert_eq!(format!("{:5}", "th\u{e9}"), "thé  ");
}Run

Base usage: 针对整数进行格式化生成字符串

fn main(){
    assert_eq!(format!("{:+}", 1234), "+1234");
    assert_eq!(format!("{:+x}", 1234), "+4d2");
    assert_eq!(format!("{:+#x}", 1234), "+0x4d2");
    assert_eq!(format!("{:b}", 1234), "10011010010");
    assert_eq!(format!("{:#b}", 1234), "0b10011010010");
    assert_eq!(format!("{:#20b}", 1234), "       0b10011010010");
    assert_eq!(format!("{:<#20b}", 1234), "0b10011010010       ");
    assert_eq!(format!("{:^#20b}", 1234), "   0b10011010010    ");
   assert_eq!(format!("{:>+#15x}", 1234), "         +0x4d2");
   assert_eq!(format!("{:>+#015x}", 1234), "+0x0000000004d2");
}Run

Base usage: 针对浮点数进行格式化生成字符串

fn main(){
    assert_eq!(format!("{:.4}", 1234.5678), "1234.5678");
    assert_eq!(format!("{:.2}", 1234.5618), "1234.56");
    assert_eq!(format!("{:.2}", 1234.5678), "1234.57");
    assert_eq!(format!("{:<10.4}", 1234.5678), "1234.5678 ");
    assert_eq!(format!("{:^12.2}", 1234.5618), "  1234.56   ");
    assert_eq!(format!("{:0^12.2}", 1234.5678), "001234.57000");
    assert_eq!(format!("{:e}", 1234.5678), "1.2345678e3");
}Run

Base usage: 自定义类型格式化生成字符串,必须实现Display

use std::fmt::{self, Formatter, Display};
struct City {
    name: &'static str,
    lat: f32,
    lon: f32,
}
impl Display for City {
    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!(f, "{}: {:.3}°{} {:.3}°{}",
          self.name, self.lat.abs(), lat_c, self.lon.abs(), lon_c)
   }
}
fn main() {
   let city = City { name: "Beijing", lat: 39.90469, lon: -116.40717 };
   assert_eq!(format!("{}", city), "Beijing: 39.905°N 116.407°W");
   println!("{}", city);
}Run