File tree 1 file changed +33
-6
lines changed
1 file changed +33
-6
lines changed Original file line number Diff line number Diff line change @@ -42,13 +42,10 @@ fn main() {
42
42
43
43
## ` Into `
44
44
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
47
- necessary.
45
+ The [ ` Into ` ] trait is simply the reciprocal of the ` From ` trait. It
46
+ defines how to convert a type into another type.
48
47
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.
48
+ Calling ` into() ` typically requires us to specify the result type as the compiler is unable to determine this most of the time.
52
49
53
50
``` rust,editable
54
51
use std::convert::Into;
@@ -72,5 +69,35 @@ fn main() {
72
69
}
73
70
```
74
71
72
+ ## ` From ` and ` Into ` are interchangable
73
+
74
+ ` From ` and ` Into ` are designed to be complementary.
75
+ We do not need to provide an implementation for both traits.
76
+ If you have implemented the ` From ` trait for your type, ` Into ` will call it
77
+ when necessary.
78
+
79
+ ``` rust,editable
80
+ use std::convert::From;
81
+
82
+ #[derive(Debug)]
83
+ struct Number {
84
+ value: i32,
85
+ }
86
+
87
+ // Define `From`
88
+ impl From<i32> for Number {
89
+ fn from(item: i32) -> Self {
90
+ Number { value: item }
91
+ }
92
+ }
93
+
94
+ fn main() {
95
+ let int = 5;
96
+ // use `Into`
97
+ let num: Number = int.into();
98
+ println!("My number is {:?}", num);
99
+ }
100
+ ```
101
+
75
102
[ `From` ] : https://doc.rust-lang.org/std/convert/trait.From.html
76
103
[ `Into` ] : https://doc.rust-lang.org/std/convert/trait.Into.html
You can’t perform that action at this time.
0 commit comments