3 The [`From`] and [`Into`] traits are inherently linked, and this is actually part of
4 its implementation. If you are able to convert type A from type B, then it
5 should be easy to believe that we should be able to convert type B to type A.
9 The [`From`] trait allows for a type to define how to create itself from another
10 type, hence providing a very simple mechanism for converting between several
11 types. There are numerous implementations of this trait within the standard
12 library for conversion of primitive and common types.
14 For example we can easily convert a `str` into a `String`
18 let my_string = String::from(my_str);
21 We can do similar for defining a conversion for our own type.
24 use std::convert::From;
31 impl From<i32> for Number {
32 fn from(item: i32) -> Self {
33 Number { value: item }
38 let num = Number::from(30);
39 println!("My number is {:?}", num);
45 The [`Into`] trait is simply the reciprocal of the `From` trait. That is, if you
46 have implemented the `From` trait for your type, `Into` will call it when
49 Using the `Into` trait will typically require specification of the type to
50 convert into as the compiler is unable to determine this most of the time.
51 However this is a small trade-off considering we get the functionality for free.
54 use std::convert::From;
61 impl From<i32> for Number {
62 fn from(item: i32) -> Self {
63 Number { value: item }
69 // Try removing the type declaration
70 let num: Number = int.into();
71 println!("My number is {:?}", num);
75 [`From`]: https://doc.rust-lang.org/std/convert/trait.From.html
76 [`Into`]: https://doc.rust-lang.org/std/convert/trait.Into.html