]> git.proxmox.com Git - rustc.git/blob - src/doc/rust-by-example/src/conversion/from_into.md
New upstream version 1.49.0+dfsg1
[rustc.git] / src / doc / rust-by-example / src / conversion / from_into.md
1 # `From` and `Into`
2
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.
6
7 ## `From`
8
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.
13
14 For example we can easily convert a `str` into a `String`
15
16 ```rust
17 let my_str = "hello";
18 let my_string = String::from(my_str);
19 ```
20
21 We can do similar for defining a conversion for our own type.
22
23 ```rust,editable
24 use std::convert::From;
25
26 #[derive(Debug)]
27 struct Number {
28 value: i32,
29 }
30
31 impl From<i32> for Number {
32 fn from(item: i32) -> Self {
33 Number { value: item }
34 }
35 }
36
37 fn main() {
38 let num = Number::from(30);
39 println!("My number is {:?}", num);
40 }
41 ```
42
43 ## `Into`
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.
48
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.
52
53 ```rust,editable
54 use std::convert::From;
55
56 #[derive(Debug)]
57 struct Number {
58 value: i32,
59 }
60
61 impl From<i32> for Number {
62 fn from(item: i32) -> Self {
63 Number { value: item }
64 }
65 }
66
67 fn main() {
68 let int = 5;
69 // Try removing the type declaration
70 let num: Number = int.into();
71 println!("My number is {:?}", num);
72 }
73 ```
74
75 [`From`]: https://doc.rust-lang.org/std/convert/trait.From.html
76 [`Into`]: https://doc.rust-lang.org/std/convert/trait.Into.html