From and Into
Types implement From and Into to facilitate type conversions:
1. fn main() {
2. let s = String::from("hello");
3. let addr = std::net::Ipv4Addr::from([127, 0, 0, 1]);
4. let one = i16::from(true);
5. let bigger = i32::from(123i16);
6. println!("{s}, {addr}, {one}, {bigger}");
7. }
Into is automatically implemented when From is implemented:
1. fn main() {
2. let s: String = "hello".into();
3. let addr: std::net::Ipv4Addr = [127, 0, 0, 1].into();
4. let one: i16 = true.into();
5. let bigger: i32 = 123i16.into();
6. println!("{s}, {addr}, {one}, {bigger}");
7. }
- That’s why it is common to only implement
From, as your type will getIntoimplementation too. - When declaring a function argument input type like “anything that can be converted into a
String”, the rule is opposite, you should useInto. Your function will accept types that implementFromand those that only implementInto.
