小编600*_*005的帖子

为什么 Rust 允许具有错误返回类型的代码,但只允许带有尾随分号?

考虑以下 Rust 代码:

fn f() -> i32 {
    loop {
        println!("Infinite loop!");
    }
    println!("Unreachable");
}
Run Code Online (Sandbox Code Playgroud)

尽管返回类型是错误的,但它会编译(带有警告)并运行。似乎编译器()对最后一行中的返回类型没有问题,因为它检测到此代码无法访问。

但是,如果我们删除最后一个分号:

fn f() -> i32 {
    loop {
        println!("Infinite loop!");
    }
    println!("Unreachable")
}
Run Code Online (Sandbox Code Playgroud)

然后代码不再编译,给出一个类型错误:

error[E0308]: mismatched types
  --> src/main.rs:14:5
   |
14 |     println!("Unreachable")
   |     ^^^^^^^^^^^^^^^^^^^^^^^ expected `i32`, found `()`
   |
   = note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)
Run Code Online (Sandbox Code Playgroud)

为什么是这样?()在这两个代码片段中,返回类型不是相同的吗?


注意:我有兴趣了解为什么 Rust 编译器在这两个示例上的行为不同,即 Rust 编译器是如何实现的。从语言设计的角度来看,我并不是要问一个关于它“应该”如何表现的哲学问题(我知道这样的问题可能会偏离主题)。

return-type unreachable-code rust

9
推荐指数
1
解决办法
294
查看次数

标签 统计

return-type ×1

rust ×1

unreachable-code ×1