rust:Using the format! macro,如何使用 format! 宏

内容纲要

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);
}
点赞

发表评论

电子邮件地址不会被公开。 必填项已用*标注