简体   繁体   中英

Why doesn't Rust infer the never type?

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() -> ! { 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM