rust: How to Use the format! Macro

2020年11月23日 96点热度 2人点赞 0条评论
内容目录

Using the format! macro

format! is a Rust macro that is essentially similar to the usage of String.Format() in C#.

There is an additional way to combine strings, which can also be used to combine them with other data types, such as numbers.

It provides another way to combine strings and can combine different data types, such as numbers.

Its definition is as follows:

#[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
    }}
}

Its usage examples are as follows:

fn main() {
    // Right-side &str string
    let s1 = format!("I have a {}", "apple");
    println!("{}",s1);
// Right-side String
let apple = String::from("apple");
let s2 = format!("I have a {}", apple);

println!("{}",s2);

// Other data types

let number = format!("number:{}",666);
println!("{}",number);

// Set in any position based on parameter index
let s3 = format!("{0}, {0}, {0}, {1}!", "duck", "goose");
println!("{}",s3);

// Get supplement from variable based on parameter name
let introduction = format!(
    "My name is {surname}, {forename} {surname}",
    surname = "Bond",
    forename = "James"
);
println!("{}", introduction);

}

痴者工良

高级程序员劝退师

文章评论