Skip to content

Commit

Permalink
Example why our TryFRom is better
Browse files Browse the repository at this point in the history
  • Loading branch information
rklaehn committed Jul 3, 2024
1 parent b751e82 commit fb66a4a
Showing 1 changed file with 18 additions and 2 deletions.
20 changes: 18 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,24 @@ Here we define conversions from `GetRequest` to `StoreRequest`, from `StoreReque

The generated [From] conversions are straightforward. Obviously it is always possible to convert from an enum case to the enum itself.

We also generate [TryFrom] conversions from the enum to each variant, as well as from a reference to the enum to a reference to the variant. The conversions that take a value are different than the ones from [derive_more]: they return
the unmodified input in the error case, allowing to chain conversion attempts.
We also generate [TryFrom] conversions from the enum to each variant, as well as from a reference to the enum to a reference to the variant.

The conversions that take a value are different than the ones from [derive_more]: they return the unmodified input in the error case, allowing to chain conversion attempts.

```rust
let request = ...
match GetRequest::try_from(request) {
Ok(get) => // handle get request
Err(request) => {
// I still got the request and can try something else
match PutRequest::try_from(request) {
...
}
}
}
```

The conversions that take a reference just return a `&'static str` as the error type. References are `Copy`, so we can always retry anyway.

[From]: https://doc.rust-lang.org/std/convert/trait.From.html
[TryFrom]: https://doc.rust-lang.org/std/convert/trait.TryFrom.html
Expand Down

0 comments on commit fb66a4a

Please sign in to comment.