使用 {} 初始化 Rust 中的新字符串

Ant*_*ead 3 rust

{}当我尝试使用以下命令使用占位符初始化字符串时:

let range_from: u32 = 1;
let range_to: u32 = 101;
let insert_message = String::new("Please input Your guess in the range from {} to {}.", range_from, range_to);
println!("{}", insert_message);
// snip
println!("{}", insert_message);
Run Code Online (Sandbox Code Playgroud)

它抛出以下错误:

提供 3 个参数 | | | 预期 1 个参数

at5*_*321 6

String::new不能那样做。您可以使用format!宏,如下所示:

let insert_message = format!("Please input Your guess in the range from {} to {}.", range_from, range_to);
Run Code Online (Sandbox Code Playgroud)

或者,从 Rust 1.58 开始,您也可以这样做:

let insert_message = format!("Please input Your guess in the range from {range_from} to {range_to}.");
Run Code Online (Sandbox Code Playgroud)

请参阅了解更多信息。