我认为这应该很简单,但我的 Google 能力很弱。我正在尝试使用 u32 变量在 Rust 中构建一个字符串。在 C 中,我会使用 snprintf,如下所示:
使用 C 中的变量(如 printf 中的变量)创建 char 数组
但我找不到任何关于如何在 Rust 中做到这一点的信息。
Exa*_*ast 21
在 Rust 中,首选是字符串格式化。
fn main() {
let num = 1234;
let str = format!("Number here: {num}");
println!("str is \"{str}\"");
// Some types only support printing with debug formatting with :?
let vec = vec![1, 2, 3];
println!("vec is {vec:?}");
// Note that you can only inline variables.
// Values and expressions cannot be inlined:
println!("{} + {} = {}", 1, 2, 1 + 2);
}
Run Code Online (Sandbox Code Playgroud)
或者(适用于旧版本的 Rust),您可以将变量写在字符串后面:
fn main() {
let num = 1234;
let str = format!("Number here: {}", num);
println!("str is \"{}\"", str);
}
Run Code Online (Sandbox Code Playgroud)
虽然功能相同,但默认 linter Clippy会建议在模式下运行时编写第一个版本pedantic。
这并不总是有效,特别是当变量不支持默认格式化程序时。文档中有更多关于字符串格式化的详细信息,包括更多显示设置以及如何实现自定义结构的格式化。
在大多数语言中,该概念的术语是“字符串格式化”(例如在 Rust、Python 或 Java 中)或“字符串插值”(例如在 JavaScript 或 C# 中)之一。
只需使用格式即可!宏。
fn main() {
let a = format!("test");
assert_eq!(a, "test");
let b = format!("hello {}", "world!");
assert_eq!(b, "hello world!");
let c = format!("x = {}, y = {y}", 10, y = 30);
assert_eq!(c, "x = 10, y = 30");
}
Run Code Online (Sandbox Code Playgroud)
只需使用.to_string()方法即可。
fn main() {
let i = 5;
let five = String::from("5");
assert_eq!(five, i.to_string());
}
Run Code Online (Sandbox Code Playgroud)