3 ms·
More concretely, it's a pain to have to implement the same functions over and over for slightly different types, even when you're basically doing the same thing
by Smaug123 4y ago
More concretely, it's a pain to have to implement the same functions over and over for slightly different types, even when you're basically doing the same thing every time. Specifically, `Option` and `Result`, for example, both have `map` implemented for them (that's one lot of duplication), but also the consumers of the data structures need to know whether they've got an `Option` or a `Result` (and that's another lot of duplication if you want to allow consumers to use either an `Option` or a `Result` depending on what happens to be locally convenient to them). Sometimes you really do want to do different things depending on whether you've got an `Option` or a `Result`, but much of the time you don't care; you're only using it to signal errors, and you have no particular opinion on how you do so.
The example in the top comment allows you to implement what it means for a type to "have a `map` function". So it doesn't get rid of the duplicated effort on the "supply side" - we still have to implement the `Mappable` trait for each of `Result` and `Option` individually - but it allows the consumer to not care whether it's got an `Option` or a `Result`, by using only the `Mappable` trait instead. That is newly possible because the GAT feature allows the definition of a `Mappable` trait which contains fresh generics, and `map` is inherently a generic function.
- tialaramex 4y agoResult and Option both implement Try, so if you actually just want to know whether to keep going or give up, the Try trait will give you a ControlFlow which says exactly that regardless of whether your input is an Option or a Result