From and Into

Types implement From and Into to facilitate type conversions. Unlike as, these traits correspond to lossless, infallible 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(123_i16);
  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 = 123_i16.into();
  6.     println!("{s}, {addr}, {one}, {bigger}");
  7. }

This slide should take about 5 minutes.

  • That’s why it is common to only implement From, as your type will get Into implementation too.
  • When declaring a function argument input type like “anything that can be converted into a String“, the rule is opposite, you should use Into. Your function will accept types that implement From and those that only implement Into.