Make an nullopt if an error is returned
paulfd opened this issue · 2 comments
Hi!
More as a nice thing to have than anything, would it be possible somehow to write :
tl::optional<T> opt = my_function(...).value_or(tl::nullopt);
assuming my_function
returns a tl::expected<T, E>
? I tried some different syntax but had to fall back to a more classical if
(which is fine).
There is certainly a value of having both tl::expected
and tl::optional
playing together in a team.
I would say the convertions from one another could be added, like:
tl::optional<T> opt = some_expected.value_or_none();
as well as something along these lines:
tl::expected<T,E> exp = some_optional.value_or_err([]()->E{ ... });
An example is how this is made in Rust, where there are seamless transitions between the two.
- https://doc.rust-lang.org/std/result/enum.Result.html#method.ok
- https://doc.rust-lang.org/std/option/enum.Option.html#method.ok_or
(for whoever is unfamiliar with Rust, Optional<T>
there maps to tl::optional<T>
here, and Result<T,E>
maps to tl::expected<T,E>
, in principle)
Having such expressiveness nicely simplifies code and makes it much clearer that workarounds with if/elses.
Exactly - was thinking the same thing in terms of being able to convert between expected and optional
As an optional is like an expected with a void error type, which I don't think is allowed, but could give a way to do it?
(including potentially from and_then
if trying to overload in some way, though that would then implicitly drop the error, or could have another function.
Another could be that map_error
/transform_error
could just return nullopt as well, (or just map/transform_to_optional, or to_optional)?
Was wondering which things make most sense?