将任何类型转换成 String
只要为一个类型实现了 ToString ,就可以将任何类型转换成 String 。事实上,这种方式并不是最好
的,大家还记得 fmt::Display 特征吗?它可以控制一个类型如何打印,在实现它的时候还会自动实现
ToString 。
- 🌟🌟
use std::fmt;
struct Point {
x: i32,
y: i32,
}
impl fmt::Display for Point {
// 实 现 fmt 方 法
}
fn main() {
let origin = Point { x: 0, y: 0 };
// 填 空
assert_eq!(origin., “The point is (0, 0)”);
assert_eq!(format!(), “The point is (0, 0)”);
println!(“Success!”)
}
解析 String - 🌟🌟🌟 使用 parse 方法可以将一个 String 转换成 i32 数字,这是因为在标准库中为 i32 类型
实现了 FromStr : : impl FromStr for i32
// 为 了 使 用from_str
方 法, 你 需 要 引 入 该 特 征 到 当 前 作 用 域 中
use std::str::FromStr;
fn main() {
let parsed: i32 = “5”..unwrap();
let turbo_parsed = “10”..unwrap();
let from_str = __.unwrap();
let sum = parsed + turbo_parsed + from_str;
assert_eq!(sum, 35);
println!(“Success!”)
} - 🌟🌟 还可以为自定义类型实现 FromStr 特征
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: Vec<&str> = s.trim_matches(|p| p == ‘(’ || p == ‘)’ )
.split(‘,’)
.collect();
let x_fromstr = coords[0].parse::()?;
let y_fromstr = coords[1].parse::()?;
Ok(Point { x: x_fromstr, y: y_fromstr })
}
}
fn main() {
// 使 用 两 种 方 式 填 空
// 不 要 修 改 其 它 地 方 的 代 码
let p = __;
assert_eq!(p.unwrap(), Point{ x: 3, y: 4} );
println!(“Success!”)
}