I am sure this was brought before but I was not able to find a convincing argument against it. Therefore, and within the language ergonomic discussion, I thought it might be a good time to post it here.
I find this example from the book quite annoying:
enum Message {
Quit,
ChangeColor(i32, i32, i32),
Move { x: i32, y: i32 },
Write(String),
}
fn process_message(msg: Message) {
match msg {
Message::Quit => quit(),
Message::ChangeColor(r, g, b) => change_color(r, g, b),
Message::Move { x: x, y: y } => move_cursor(x, y),
Message::Write(s) => println!("{}", s),
};
}
It is too verbose and due to indentation the code can be very annoying to read if it is deeply nested. So the question is: if you are matching an Enum variant, cannot Message::
(in this case) be implicit?
fn process_message(msg: Message) {
match msg {
Quit => quit(),
ChangeColor(r, g, b) => change_color(r, g, b),
Move { x: x, y: y } => move_cursor(x, y),
Write(s) => println!("{}", s),
};
}
I have seen ways to mitigate this (such as use Message::*
) but I think some implicitness here will be nicer. Following the argumentation line proposed the blog post
-
Applicability. It would be applicable in every situation having an enum match, a quite common piece of code in Rust
-
Power. The elided information cannot have an unwanted influence. And if you do something wrong the compiler will complain.
-
Context-dependence. What is elided is the Enum Type, so the question is if there is a way a casual reader of the code can know which type it is and where to find its definition. The variable to be matched (
msg
in this case) could come from 3 places: -
(1) it can be defined in the same function
-
(2) it can be an argument of the function being read and
-
(3) it can be the result of calling another function.
Finding the enum type and source for (1) and (2) is straight forward. For (3) it would require going to the definition fo the function.