quicli
quicli copied to clipboard
Add trait for ergonomic Options-as-Errors
Not sure if this
- is any good
- should be part of this crate (or be defined upstream somewhere)
cc @steveklabnik
I think the docs could clarify a bit more what this is useful since I am still confused. Is the use of this to eliminate having to do:
match maybe {
Some(v) => Ok(v),
None => Err("no means no"),
}
and instead do:
maybe.none_means("no means no")
In that case maybe map_none
is better? Also how is this different from map_or_else
(other than the name is better. I like map_none
personally).
Also I just realized something... 'static
as a trait bound applies to Box
values, doesn't it? That's pretty cool!
I think the docs could clarify a bit more what this is useful since I am still confused.
Rust already has support for using ?
on Option
, but it gives you a NoneError
, which we'd have to deal with somehow.
So this is a (hopefully useful) way to concisely treat None
as Err
and include a message. For example, imagine you are dealing with serde-jsons's Value type, and want to get a field as i64:
let v = json!({ "a": 64, "b": big, "c": 256.0 });
// ...
let a = v["a"].as_i64().none_means("a field wasn't an integer")?;
Thinking about it, it's very similar to .expect
but returns an error instead of panicking. Maybe we can find a name that fits this?
Also how is this different from map_or_else (other than the name is better. I like map_none personally).
It's not really map
, but ok_or_else
. It is technically equivalent to doing .ok_or_else(|| err_msg(reason))
. I'm just giving this pattern a name for convenience.
Why not call this feature ok_or_err
- it makes much more sense IMO and sticks closely to the existing Option
methods.
So
match maybe {
Some(v) => Ok(v),
None => Err("error msg"),
}
would be rewritten as:
maybe.ok_or_err("error msg")
Yeah, ok_or_err
fits pretty good next to ok_or_else
.
I kinda wanted to go with a not-similar name because I don't want user to need to think about that this maps an Option to a Result. I want you to use to slap ?
on an Option and have it print a nice error. ok_or_err
tells me what it does, but something like none_means
tells me what it should be used for. (I agree that none_means
is not a good name, though.)
I'm not found of that, that's just about the same as
maybe.ok_or("error msg")?