rust - Can the compiler tell when a `break` is never reached -
i have code:
fn make_guess() -> u32 { loop { let mut guess = string::new(); io::stdin().read_line(&mut guess) .ok() .expect("failed read line"); match guess.trim().parse() { ok(num) => return num, err(_) => { println!("please input number!"); continue; } }; break; } }
when run code, compiler complains about:
expected `u32`, found `()`
seemingly break;
results in returning void value. however, there no way break;
reached because of return
, continue
.
in fact, if remove break;
works fine.
is bug in compiler or intended reason?
a loop
expression doesn't contain break
expression evaluates !
(i.e. diverges), compatible types.
fn main() { let _x: u32 = loop {}; // compiles }
on other hand, loop
break
returns ()
, compatible ()
type.
fn main() { let _x: u32 = loop { break; }; // mismatched types: expected `u32`, found `()` }
in make_guess
function, compiler adds implicit return
before loop
expression. !
compatible u32
, ()
not. (this implicit return
seems occur diverging expressions, if end ;
.) adding break
statement in loop changes type of loop
expression. not matter break
unreachable.
heads @ker noticing type of loop
changes based on presence or absence of break
expression in body.
Comments
Post a Comment