Rust:相同的代码编译时出现警告或失败时出现错误



我正在尝试使用在Windows上学习本教程

D:srcrusthecto>cargo --version
cargo 1.57.0 (b2e52d7ca 2021-10-21)
D:srcrusthecto>rustc --version
rustc 1.57.0 (f1edd0429 2021-11-29)

我在两个项目目录中有以下代码:

use std::io;
use std::io::Read;
fn die(e: std::io::Error) {
panic!(e);
}
fn main() {
let ctrl_q = 'q' as u8 & 0b1_1111;
for b in io::stdin().bytes() {
match b {
Ok(b) => {
let c = b as char;
if c.is_control() {
println!("{:#b} r", b);
}
else {
println!("{:?} ({})r", b, c);
}
if b == ctrl_q {
break;
}
},
Err(err) => die(err),
}
}
}

在删除targetCargo.lock之后,在一个项目中,我得到了以下输出:

C:temphecto-tutorial-die-on-input-error>cargo build
Updating crates.io index
Compiling winapi v0.3.9
Compiling cfg-if v1.0.0
Compiling parking_lot_core v0.8.5
Compiling smallvec v1.7.0
Compiling scopeguard v1.1.0
Compiling bitflags v1.3.2
Compiling instant v0.1.12
Compiling lock_api v0.4.5
Compiling crossterm_winapi v0.9.0
Compiling parking_lot v0.11.2
Compiling crossterm v0.22.1
Compiling hecto v0.1.0 (C:temphecto-tutorial-die-on-input-error)
warning: panic message is not a string literal
--> srcmain.rs:5:12
|
5 |     panic!(e);
|            ^
|
= note: `#[warn(non_fmt_panics)]` on by default
= note: this usage of panic!() is deprecated; it will be a hard error in Rust 2021
= note: for more information, see <https://doc.rust-lang.org/nightly/edition-guide/rust-2021/panic-macro-consistency.html>
help: add a "{}" format string to Display the message
|
5 |     panic!("{}", e);
|            +++++
help: or use std::panic::panic_any instead
|
5 |     std::panic::panic_any(e);
|     ~~~~~~~~~~~~~~~~~~~~~
warning: `hecto` (bin "hecto") generated 1 warning
Finished dev [unoptimized + debuginfo] target(s) in 13.22s

而在另一个我得到

D:srcrusthecto>cargo build
Updating crates.io index
Compiling winapi v0.3.9
Compiling parking_lot_core v0.8.5
Compiling cfg-if v1.0.0
Compiling scopeguard v1.1.0
Compiling smallvec v1.7.0
Compiling bitflags v1.3.2
Compiling instant v0.1.12
Compiling lock_api v0.4.5
Compiling crossterm_winapi v0.9.0
Compiling parking_lot v0.11.2
Compiling crossterm v0.22.1
Compiling hecto v0.1.0 (D:srcrusthecto)
error: format argument must be a string literal
--> srcmain.rs:5:12
|
5 |     panic!(e);
|            ^
|
help: you might be missing a string literal to format with
|
5 |     panic!("{}", e);
|            +++++
error: could not compile `hecto` due to previous error

你知道为什么它在一个项目中编译得很好,但在另一个项目却失败了吗?

panic!宏的行为在Rust 2021版本中发生了一些变化,使其与其他格式系列宏更加一致。迁移指南中有整整一章专门介绍了这一点。

修复程序以及包含详细信息的链接也显示在您得到的错误消息中:

= note: `#[warn(non_fmt_panics)]` on by default
= note: this usage of panic!() is deprecated; it will be a hard error in Rust 2021
= note: for more information, see <https://doc.rust-lang.org/nightly/edition-guide/rust-2021/panic-macro-consistency.html>
help: add a "{}" format string to Display the message
|
5 |     panic!("{}", e);
|            +++++
help: or use std::panic::panic_any instead
|
5 |     std::panic::panic_any(e);
|     ~~~~~~~~~~~~~~~~~~~~~

最新更新