TryFrom<T>TryInto<U>From, Into 的安全版本,其方法 try_from() 的返回类型为 Result<ok_t, error_t>,可以更加灵活地处理错误.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// Tuple implementation
impl TryFrom<(i16, i16, i16)> for Color {
type Error = IntoColorError;
fn try_from(tuple: (i16, i16, i16)) -> Result<Self, Self::Error> {
let (r, g, b) = tuple;
if r < 0 || r > 255 || g < 0 || g > 255 || b < 0 || b > 255 {
return Err(IntoColorError::IntConversion);
}
Ok(Color {
red: r as u8,
green: g as u8,
blue: b as u8,
})
}
}

/// ===== main.rs =====
let c1 = Color::try_from((183, 65, 14));
println!("{:?}", c1);
// or take slice within round brackets and use TryInto
let c4: Result<Color, _> = (&v[..]).try_into();
println!("{:?}", c4);

From, Into 一样,实现了 T: TryFrom<U> 就自动实现了 U: TryInto<T>,对 U 类型就可以使用 try_into() 方法了.