4 ms·
It might be worth pointing out that this Rust: #[derive(Debug)] enum ConfigError { Io(io::Error), Parse(ParseIntError), }
by twic 10y ago
It might be worth pointing out that this Rust:
#[derive(Debug)]
enum ConfigError {
Io(io::Error),
Parse(ParseIntError),
}
impl From<io::Error> for ConfigError {
fn from(err: io::Error) -> ConfigError {
ConfigError::Io(err)
}
}
impl From<ParseIntError> for ConfigError {
fn from(err: ParseIntError) -> ConfigError {
ConfigError::Parse(err)
}
}
fn read_config() -> Result<i32, ConfigError> {
Result::Ok(parse_int(read_config_file()?)?)
}
// given the following
fn parse_int(str: String) -> Result<i32, ParseIntError> { ... }
fn read_config_file() -> Result<String, io::Error> { ... }
Is, in a sense, the equivalent of this Java:
int readConfig() throws IOException, ParseException {
return parseInt(readConfigFile());
}
// given the following
int parseInt(String str) throws ParseException { ... }
String readConfigFile() throws IOException { ... }
The reason i say that is that this:
throws IOException, ParseException
Is essentially a sum type. It says that if this method results in a failure value, it can fail with one of two types of failure values. It might not look like a new type, because in Java, types are almost always nominal, and this is structural, but that's what it is. I think that throw and catch clauses are the only place that Java will let you define an ad-hoc sum type. You have to use polymorphism everywhere else you want a variety of types.
Whereas in Rust, there are no structural sum types, and so the only way to make something resembling a sum type is:
enum ConfigError {
Io(io::Error),
Parse(ParseIntError),
}
Which means you also have to write the machinery to convert between the types.
I wonder if it would help to have a compiler- or library-defined From impl for all newtype enum variants (or all newtype structs more generally), that makes the variant from its argument. Or maybe it could be derived. It would wipe out a lot of this boilerplate.
- Rusky 10y agoI would love a `#[derive(From)]` for newtype structs and enum variants. Would bring Rust error handling back below Java in boilerplate levels. :)
- killercup 10y agoThere are some crates that add a derive for errors, but most people tend to use error-chain or quick-error. Both give you the boilerplate pretty much for free, with various other advantages. E.g., using error-chain, you can just write the above code as error_chain! { foreign_links { Io(io::Error); Parse(ParseIntError); } } and it'll even generate an aliased `Result` type as well as fancy chaining support.
- Rusky 10y agoRight- error_chain is just a bit too much magic for me compared to what #[derive(From)] would do.
- steveklabnik 10y agoCheck out https://crates.io/crates/newtype_derive https://crates.io/crates/newtype_derive
- twic 10y agoVery nice. Now we just need enum variants to be first-class types, and some syntax for deriving on them.