File tree 2 files changed +46
-0
lines changed
2 files changed +46
-0
lines changed Original file line number Diff line number Diff line change 36
36
37
37
- [ Conversion] ( conversion.md )
38
38
- [ ` From ` and ` Into ` ] ( conversion/from_into.md )
39
+ - [ ` TryFrom ` and ` TryInto ` ] ( conversion/try_from_try_into.md )
39
40
- [ To and from ` String ` s] ( conversion/string.md )
40
41
41
42
- [ Expressions] ( expression.md )
Original file line number Diff line number Diff line change
1
+ # ` TryFrom ` and ` TryInto `
2
+
3
+ Similar to [ ` From ` and ` Into ` ] [ from-into ] , [ ` TryFrom ` ] and [ ` TryInto ` ] are
4
+ generic traits for converting between types. Unlike ` From ` /` Into ` , the
5
+ ` TryFrom ` /` TryInto ` traits are used for fallible conversions, and as such,
6
+ return [ ` Result ` ] s.
7
+
8
+ [ from-into ] : conversion/from_into.html
9
+ [ `TryFrom` ] : https://doc.rust-lang.org/std/convert/trait.TryFrom.html
10
+ [ `TryInto` ] : https://doc.rust-lang.org/std/convert/trait.TryInto.html
11
+ [ `Result` ] : https://doc.rust-lang.org/std/result/enum.Result.html
12
+
13
+ ``` rust
14
+ use std :: convert :: TryFrom ;
15
+ use std :: convert :: TryInto ;
16
+
17
+ #[derive(Debug , PartialEq )]
18
+ struct EvenNumber (i32 );
19
+
20
+ impl TryFrom <i32 > for EvenNumber {
21
+ type Error = ();
22
+
23
+ fn try_from (value : i32 ) -> Result <Self , Self :: Error > {
24
+ if value % 2 == 0 {
25
+ Ok (EvenNumber (value ))
26
+ } else {
27
+ Err (())
28
+ }
29
+ }
30
+ }
31
+
32
+ fn main () {
33
+ // TryFrom
34
+
35
+ assert_eq! (EvenNumber :: try_from (8 ), Ok (EvenNumber (8 )));
36
+ assert_eq! (EvenNumber :: try_from (5 ), Err (()));
37
+
38
+ // TryInto
39
+
40
+ let result : Result <EvenNumber , ()> = 8i32 . try_into ();
41
+ assert_eq! (result , Ok (EvenNumber (8 )));
42
+ let result : Result <EvenNumber , ()> = 5i32 . try_into ();
43
+ assert_eq! (result , Err (()));
44
+ }
45
+ ```
You can’t perform that action at this time.
0 commit comments