Skip to content

Commit

Permalink
Merge pull request #1247 from adamchalmers/master
Browse files Browse the repository at this point in the history
fix 1037: add the TryFrom chapter back in
  • Loading branch information
marioidival authored Sep 6, 2019
2 parents e76be6b + 1952353 commit 1626088
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@

- [Conversion](conversion.md)
- [`From` and `Into`](conversion/from_into.md)
- [`TryFrom` and `TryInto`](conversion/try_from_try_into.md)
- [To and from `String`s](conversion/string.md)

- [Expressions](expression.md)
Expand Down
45 changes: 45 additions & 0 deletions src/conversion/try_from_try_into.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# `TryFrom` and `TryInto`

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.

[from-into]: conversion/from_into.html
[`TryFrom`]: https://doc.rust-lang.org/std/convert/trait.TryFrom.html
[`TryInto`]: https://doc.rust-lang.org/std/convert/trait.TryInto.html
[`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html

```rust
use std::convert::TryFrom;
use std::convert::TryInto;

#[derive(Debug, PartialEq)]
struct EvenNumber(i32);

impl TryFrom<i32> for EvenNumber {
type Error = ();

fn try_from(value: i32) -> Result<Self, Self::Error> {
if value % 2 == 0 {
Ok(EvenNumber(value))
} else {
Err(())
}
}
}

fn main() {
// TryFrom

assert_eq!(EvenNumber::try_from(8), Ok(EvenNumber(8)));
assert_eq!(EvenNumber::try_from(5), Err(()));

// TryInto

let result: Result<EvenNumber, ()> = 8i32.try_into();
assert_eq!(result, Ok(EvenNumber(8)));
let result: Result<EvenNumber, ()> = 5i32.try_into();
assert_eq!(result, Err(()));
}
```

0 comments on commit 1626088

Please sign in to comment.