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 use regex to match a double quote in Rust?
- How to create a HashMap of structs in Rust?
- How to replace a capture group using Rust regex?
- How to match the end of a line in a Rust regex?
- How to modify an existing entry in a Rust HashMap?
- How do I identify unused variables in Rust?
- How to use negation in Rust regex?
- Regex example to match multiline string in Rust?
- How to use a Rust HashMap in a struct?
- How do I use a variable number of arguments in Rust?
See more codes...