9 ms·
Was the expect method supposed to be named except, as in exception? That would make a lot more sense.
by QuercusMax 9y ago
Was the expect method supposed to be named except, as in exception? That would make a lot more sense.
- Pxtl 9y agoNot a Rust guy, but it looks like a way to say "this option value is required and if it is not present, crash with the following error". So "expect" is a fair name, since it means a value is expected and the absence of a value is unexpected. I could see "required" or "require" as a better name. Or even just break the "positive names" rule and go with "notOptional".
- eriknstr 9y agoLooking at it that way, I think it's possible to make "expect" more comfortable to read by how you phrase your error messages. Instead of let mut file = File::open("conf.json") .expect("could not open file"); and let config: Value = serde::from_reader(file) .expect("config has invalid json"); and let jenkins_server = config.get("jenkins_server") .expect("jenkins_server key not in config") .as_str() .expect("jenkins_server key is not a string"); One could write let mut file = File::open("conf.json") .expect("Need to be able to open file `conf.json'."); and let config: Value = serde::from_reader(file) .expect("The file `conf.json' must contain valid JSON."); and let jenkins_server = config.get("jenkins_server") .expect("The config must have a key named `jenkins_server'.") .as_str() .expect("The config value of `jenkins_server' must be a string."); Something like that.
- erickt 9y agoThat is a good point. I'm going to have to start being more positive in my expectations :)
- swsieber 9y agoI think it's like Assert. You pass an error message the same way you pass an error message to assert.
- erickt 9y agoIf I recall correctly we just couldn't come up with a great name for it. To me "expect" is a positive action, but the argument is about it failing to meet the expectation. Semantically I like `thing.unwrap_or(|| panic!("failure message"))`. It feels more like what I would want to say, but it just is so wordy. Ultimately I'm happy we just picked something and moved on, but still mildly annoys me whenever I write it. If only we found that perfect method name way back when...
- AlphaSite 9y agoThe java optional api uses orElseThrow which I think is quite clear.
- bluejekyll 9y agoAgreed, I've never liked 'expect' either; 'or_else_panic(msg)' would be much clearer Edit: 'or_panic(msg)' would be shorter and also good.
- erickt 9y agoI think that was one of the proposed variations, but we ended up picking the shorter .expect to cut down on repetition. We expected (ha) that this function would be used in these one-offs, so we wanted something more efficient.
- bluejekyll 9y agoAs an old Java hack, my allowance for repetition is high. Especially when using and IDE that basically writes the code for me ;)
- e12e 9y agootherwise(msg)?
- MaxGabriel 9y ago