-
Notifications
You must be signed in to change notification settings - Fork 13.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Possibly bad example in documentation for 'unreachable!()' #18876
Comments
This example certainly is more complicated than it has to be. |
Your example literally warns that the Rust understands that |
For example this simple function in
Here we are asserting that the program is in an inconsistent state if both removes yield anything other than Similarly you would use |
@steveklabnik do you mean the example in the documentation or my proposed example is overly complicated? @gankro ah, I see what it's purpose is now then. Perhaps the documentation should make it clear that there is no need to mark code that that literally cannot be reached, only code which shouldn't be reached. I think your example is much nicer as it shows a more real world example of where this macro should be used. |
The exam;ple in the documentation. |
On Reddit I learned exhaustiveness check can't understand match guards and we sometimes need to insert a seemingly unnecessary arm with wildcard pattern. fn main() {
match Some(1_i32) {
Some(n) if n >= 0 => println!("Some(Non-negative)"),
Some(n) if n < 0 => println!("Some(Negative)"),
Some(_) => unreachable!(), // compile error if commented out
None => println!("None")
}
} Iterator utilities sometimes need fn divide_by_three(x: i32) -> i32 { // one of the poorest implementations of x/3
for i in std::iter::count(0_i32, 1) {
if i < 0 { panic!("i32 overflow"); }
if x < 3*i { return i; }
}
unreachable!();
}
fn main() {
println!("{}", divide_by_three(10));
} |
At present, the documentation for
unreachable!()
has an example where you could not argue that the 'unreachable' code is indeed unreachable:I would argue a better example would see a loop more like:
Perhaps I am miss understanding the purpose of this macro, in the example I provided here, is the compiler able to determine that the loop will keep going until eventually the
return sum;
is executed, and thus there is no need for theunreachable();
. In which case, I think the documentation should make it clear that in such situations the macro is not required.I'd argue it is as important to know where not to use this macro as it is when to use it.
The text was updated successfully, but these errors were encountered: