From 1952353e85acc8e960a43e25e0ebf0306b0b7359 Mon Sep 17 00:00:00 2001 From: Adam Chalmers Date: Thu, 5 Sep 2019 20:22:14 -0500 Subject: [PATCH] Revert "Remove TryFrom due to destabilization" This reverts commit 2a808e6a3d25a26702a4a4a08568904764ae1bea. --- src/SUMMARY.md | 1 + src/conversion/try_from_try_into.md | 45 +++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 src/conversion/try_from_try_into.md diff --git a/src/SUMMARY.md b/src/SUMMARY.md index 6121054342..1969ed05a5 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -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) diff --git a/src/conversion/try_from_try_into.md b/src/conversion/try_from_try_into.md new file mode 100644 index 0000000000..9e3242895b --- /dev/null +++ b/src/conversion/try_from_try_into.md @@ -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 for EvenNumber { + type Error = (); + + fn try_from(value: i32) -> Result { + 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 = 8i32.try_into(); + assert_eq!(result, Ok(EvenNumber(8))); + let result: Result = 5i32.try_into(); + assert_eq!(result, Err(())); +} +```