Skip to content

Commit fb66a4a

Browse files
committed
Example why our TryFRom is better
1 parent b751e82 commit fb66a4a

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

README.md

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,24 @@ Here we define conversions from `GetRequest` to `StoreRequest`, from `StoreReque
4141

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

44-
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
45-
the unmodified input in the error case, allowing to chain conversion attempts.
44+
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.
45+
46+
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.
47+
48+
```rust
49+
let request = ...
50+
match GetRequest::try_from(request) {
51+
Ok(get) => // handle get request
52+
Err(request) => {
53+
// I still got the request and can try something else
54+
match PutRequest::try_from(request) {
55+
...
56+
}
57+
}
58+
}
59+
```
60+
61+
The conversions that take a reference just return a `&'static str` as the error type. References are `Copy`, so we can always retry anyway.
4662

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

0 commit comments

Comments
 (0)