内容目录
Using the format! macro
format!
是一个 rust 宏,跟 C# 的 String.Format()
用法基本一致。
There is an additional way to combine strings, which can also be used to combine them with other data types, such as numbers.
能够以另一种方式去组合字符串,也可以组合不同的数据类型,例如数字。
其定义如下:
#[macro_export]
#[stable(feature = "rust1", since = "1.0.0")]
macro_rules! format {
($($arg:tt)*) => {{
let res = $crate::fmt::format($crate::__export::format_args!($($arg)*));
res
}}
}
其使用示例如下:
fn main() {
// 右侧 &str 字符串
let s1 = format!("I have a {}", "apple");
println!("{}",s1);
// 右侧 String
let apple = String::from("apple");
let s2 = format!("I have a {}", apple);
println!("{}",s2);
// 其他数据类型
let number = format!("number:{}",666);
println!("{}",number);
// 根据参数序号,任意位置设置
let s3 = format!("{0}, {0}, {0}, {1}!", "duck", "goose");
println!("{}",s3);
// 根据参数名称,从变量中获取补充
let introduction = format!(
"My name is {surname}, {forename} {surname}",
surname = "Bond",
forename = "James"
);
println!("{}", introduction);
}
文章评论