Skip to content

Commit 0a2ab00

Browse files
authored
Clarify interchangability for From and Into
Split out a section showing how we get "free" implementation of the `Into` trait if the `From` trait is already defined.
1 parent 0d22813 commit 0a2ab00

File tree

1 file changed

+33
-6
lines changed

1 file changed

+33
-6
lines changed

src/conversion/from_into.md

Lines changed: 33 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -42,13 +42,10 @@ fn main() {
4242

4343
## `Into`
4444

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.
4847

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.
5249

5350
```rust,editable
5451
use std::convert::Into;
@@ -72,5 +69,35 @@ fn main() {
7269
}
7370
```
7471

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::Into;
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+
75102
[`From`]: https://doc.rust-lang.org/std/convert/trait.From.html
76103
[`Into`]: https://doc.rust-lang.org/std/convert/trait.Into.html

0 commit comments

Comments
 (0)