Consider this Rust code:
fn loop_forever() {
loop {
}
}
fn main() {
let hello = if true { "Hello, world!" } else { loop_forever() };
println!("{}", hello);
}
The return type of loop_forever
is inferred to be ()
, so compilation fails because that's not compatible with the type of "Hello, world!"
. But the return type can be !
instead, and if I write fn loop_forever() -> ! {
instead of letting it be inferred, then it works fine. So why doesn't Rust infer this in the first place?
Rust never infers a function's return type. If not specified it defaults to ()
. The inside of the function body cannot affect the function's signature.