5 ms·
Author writes: ----- match item_option { Some(item) => { //Do something with resource println!("{}", item); } None => {} -----
by doonesbury 6y ago
Author writes:
-----
match item_option {
Some(item) => {
//Do something with resource
println!("{}", item);
}
None => {}
---------
Wouldn't this be better with design by contract by having first() enforce length>0 then turning off assertions if desired for release code? Also OP should have mentioned not matching none is an error otherwise there's no point
- ezekiel68 6y agoWouldn't this be better with design by contract... I don't believe so. No plans survive contact with "the enemy", and the enemy here is input that your system may not have control over (such as processing streaming data from an external source). If we simply turn off the check for release builds, this case would halt the system rather than provide an option to log the offending input contextual information to an error channel and perhaps ignore or recover from the situation (as appropriate).
- masklinn 6y ago> Wouldn't this be better with design by contract by having first() enforce length>0 then turning off assertions if desired for release code? I would say very much not, but maybe I'm misunderstanding what you mean, or maybe you're misunderstanding the language? What I'm getting from your suggestion is pub fn first(&self) -> &T { debug_assert!(self.len() > 0); unsafe { &* self.as_ptr() } } which is a straight UB in "safe Rust" as soon as you invoke it on an empty slice (or vec), which is completely verboten. What you could do is have a separate `NonEmpty` vector either by construction or by assertion, for which `first` wouldn't be failible (but other operations would be). > Also OP should have mentioned not matching none is an error otherwise there's no point That actually is irrelevant to the story OP is telling. They're talking about null-safety, match-completeness is an orthogonal concern (and one they don't really care for here, they just want to operate on a present value).
- aliceryhl 6y agoMaybe I misunderstand what you meant, but by having `first()` return an `Option`, you can verify at compile-time that the caller handles the empty case, whereas an assertion would not detect the issue until runtime. If the caller wants to kill the program when its empty, they can just call `.unwrap()` on the option to explicitly opt-in to a runtime check.