尝试在 Rust v0.13.0 中打印整数时出现编译错误

Compile error when trying to print an integer in Rust v0.13.0

我认为这行得通:

let x = 5;
println!("x = {}", x);

但它给出了以下编译错误:

main.rs:3:24: 3:25 error: unable to infer enough type information to locate the impl of the trait `core::fmt::Show` for the type `_`; type annotations required                                                                             
main.rs:3     println!("x = {}", x);

我错过了什么吗?

我使用的是 online Rust compiler,他们的版本是 Rust v0.13.0

错误是因为您使用的编译器太旧了。对于这个编译器,尝试显式给出一个整数类型:

let x: i32 = 5;
println!("x = {}", x);

在较新的编译器上,您的代码将按原样运行,即使没有明确指定 i32

let x = 5;
println!("x = {}", x);

您可以在 https://play.rust-lang.org/ 使用官方在线编译器,它始终是 Rust 的最新版本。