10 ms·
> Result<(), ()> is just a spicy bool. EDIT: quoted wrong part of parent, ignore above > match x { true => {} false => {} } I really
by skrtskrt 5y ago
> Result<(), ()> is just a spicy bool.
EDIT: quoted wrong part of parent, ignore above
> match x {
true => {}
false => {}
}
I really like this. Pattern matching syntax is great, nice to use in place of if/else as much as possible
- iudqnolq 5y agoI disagree. There's a clippy lint against pattern matching on bool. I also think Result has the connotation of "success or error". Plus it's always annoying when a function returns an error that doesn't implement Error and I have to wrap/replace it to make it integrate with the standard error handling ecosystem. There's a nice alternative though, which is empty struct errors. #[derive(Debug, thiserror::Error, displays of::Display)] /// Frobnicating the foo failed. struct FrobError; The advantage is the standard advantages types use, i.e. if I want to propagate it I know this specific zero sized type has a specific meaning. It'll also show a nice message if you print it.
- estebank 5y agoI like matching on bools on the same cases where someone wouldn't write braces around the body in C: whenever the corresponding expressions keep you under the line length. For example: let plural = match cases.len() > 1 { true => "s", false => "", }; Of course, you'd more likely have something like let prefix = match cases.len() { 0 => "no values".to_string(), 1 => "a value".to_string(), n => format!("{} values", n), };
- iudqnolq 5y agoInteresting. I prefer writing that as an if/else on one line when rufmt lets me, but I see your point.
- rabidferret 5y agolet plural = match cases.len() { 1.. => "s", 0 => "", }; ;P
- cyphar 5y agoThat's not the correct plural rule in English, you'd want let plural = match cases.len() { 0 | 2.. => "s", 1 => "", }; or something (though to be fair the original code snippet also handled "0" incorrectly -- should be "cases.len() != 1").
- iudqnolq 5y agoAnd also to be fair you probably don't want to be hardcoding English pluralization rules.
- rabidferret 5y agoI used to maintain a library which actually tried to implement proper English pluralization rules. I can confirm you don't want to do that.
- spullara 5y agoMy favorite thing about internationalization is that some languages have 6 different translations for different amounts.
- OJFord 5y agoHang on aren't we conflating two things in this thread? Or you quoted the wrong half of GP's comment perhaps? You can pattern match on an actual `bool`; if you use `Result<(), ()>` instead you'll have to match on `Ok(_)`/`Err(_)`, which is bad because one of your Boolean values is an 'error' now, and also because which one is is up to you (to remember)!