Skip to content

Commit 6a3fb5c

Browse files
committed
Add basic example for TryFrom/TryInto.
Fixes #1037.
1 parent 37a724a commit 6a3fb5c

File tree

2 files changed

+42
-2
lines changed

2 files changed

+42
-2
lines changed

src/SUMMARY.md

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,9 @@
3535
- [Aliasing](types/alias.md)
3636

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

4142
- [Expressions](expression.md)
4243

src/conversion/try_from_try_into.md

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# `TryFrom` and `TryInto`
2+
3+
Similar to [`From` and `Into`][from-into], [`TryFrom`] and [`TryInto`] are generic traits for converting between types. Unlike `From`/`Into`, the `TryFrom`/`TryInto` traits are used for fallible conversions, and as such, return [`Result`]s.
4+
5+
[from-into]: conversion/from_into.html
6+
[`TryFrom`]: https://doc.rust-lang.org/std/convert/trait.TryFrom.html
7+
[`TryInto`]: https://doc.rust-lang.org/std/convert/trait.TryInto.html
8+
[`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html
9+
10+
```rust
11+
#[derive(Debug, PartialEq)]
12+
struct EvenNumber(i32);
13+
14+
impl TryFrom<i32> for EvenNumber {
15+
type Error = ();
16+
17+
fn try_from(value: i32) -> Result<Self, Self::Error> {
18+
if value % 2 == 0 {
19+
Ok(EvenNumber(value))
20+
} else {
21+
Err(())
22+
}
23+
}
24+
}
25+
26+
fn main() {
27+
// TryFrom
28+
29+
assert_eq!(EvenNumber::try_from(8), Ok(EvenNumber(8)));
30+
assert_eq!(EvenNumber::try_from(5), Err(()));
31+
32+
// TryInto
33+
34+
let result: Result<EvenNumber, ()> = 8i32.try_into();
35+
assert_eq!(result, Ok(EvenNumber(8)));
36+
let result: Result<EvenNumber, ()> = 5i32.try_into();
37+
assert_eq!(result, Err(()));
38+
}
39+
```

0 commit comments

Comments
 (0)