quicli icon indicating copy to clipboard operation
quicli copied to clipboard

Add trait for ergonomic Options-as-Errors

Open killercup opened this issue 7 years ago • 7 comments

killercup avatar Jan 26 '18 23:01 killercup

Not sure if this

  • is any good
  • should be part of this crate (or be defined upstream somewhere)

cc @steveklabnik

killercup avatar Jan 26 '18 23:01 killercup

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).

vitiral avatar Jan 29 '18 03:01 vitiral

Also I just realized something... 'static as a trait bound applies to Box values, doesn't it? That's pretty cool!

vitiral avatar Jan 29 '18 03:01 vitiral

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.

killercup avatar Jan 29 '18 09:01 killercup

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")

mattgathu avatar Jan 31 '18 06:01 mattgathu

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.)

killercup avatar Jan 31 '18 08:01 killercup

I'm not found of that, that's just about the same as

maybe.ok_or("error msg")?

TeXitoi avatar Feb 06 '18 14:02 TeXitoi