面向云技术架构 - 痴者工良

  • 首页
  • 资源导航
    • 值得收藏的网站导航
    • 本站文章导航
    • 资源下载
  • 教程文档
    • kubernetes 教程
    • 多线程和异步
    • 动态编程-反射、特性、AOP
    • 表达式树
  • 隐私政策
无虑
青山一片云雾,心安即归处,山泉水洗去来时的尘土。
听风吹过松竹,自在即归处,借一壶清茶伴日出。
  1. 首页
  2. 编程语言
  3. rust
  4. 正文

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

2020年11月23日 1391点热度 0人点赞 0条评论
内容纲要

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);
}
本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可
标签: format macro rust using 如何
最后更新:2021年2月21日

痴者工良

高级程序员劝退师

点赞
< 上一篇
下一篇 >

文章评论

取消回复
You must enable javascript to see captcha here!
目录导航

COPYRIGHT © 2022 whuanle.cn. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

粤ICP备18051778号

粤公网安备 44030902003257号