rustHow to use variables in string while formatting in Rust
Variables can be used in string formatting in Rust using the format! macro. The format! macro takes a format string as its first argument, followed by the variables to be used in the format string. The format string is a string literal that contains placeholders for the variables. The placeholders are written in curly braces {} and are replaced by the variables when the format! macro is called.
For example, the following code:
let name = "John";
let age = 30;
println!("{} is {} years old", name, age);
will ### Output
John is 30 years old
The code can be broken down as follows:
- Two variables,
nameandage, are declared and assigned values. - The
format!macro is called with the format string"{} is {} years old"as its first argument, followed by the variablesnameandage. - The
format!macro replaces the placeholders{}in the format string with the values of the variablesnameandage. - The resulting string is printed to the console using the
println!macro.
For more information, see the Rust documentation on string formatting and the Rust by Example guide on string formatting.
More of Rust
- How to match whitespace with a regex in Rust?
- How to use Unicode in a regex in Rust?
- How to use regex lookahead in Rust?
- How to match a URL with a regex in Rust?
- How to use non-capturing groups in Rust regex?
- How to replace all matches using Rust regex?
- How to find the first match in a Rust regex?
- How to print a Rust HashMap?
- How to use negation in Rust regex?
- How to extract data with regex in Rust?
See more codes...