Skip to content

Commit 1626088

Browse files
authored
Merge pull request #1247 from adamchalmers/master
fix 1037: add the TryFrom chapter back in
2 parents e76be6b + 1952353 commit 1626088

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

src/SUMMARY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636

3737
- [Conversion](conversion.md)
3838
- [`From` and `Into`](conversion/from_into.md)
39+
- [`TryFrom` and `TryInto`](conversion/try_from_try_into.md)
3940
- [To and from `String`s](conversion/string.md)
4041

4142
- [Expressions](expression.md)

src/conversion/try_from_try_into.md

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
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+
```

0 commit comments

Comments
 (0)