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,
name
andage
, are declared and assigned values. - The
format!
macro is called with the format string"{} is {} years old"
as its first argument, followed by the variablesname
andage
. - The
format!
macro replaces the placeholders{}
in the format string with the values of the variablesname
andage
. - 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 replace a capture group using Rust regex?
- How to match the end of a line in a Rust regex?
- How to extract data with regex in Rust?
- How to parse a file with Rust regex?
- How to match a URL with a regex in Rust?
- How to replace strings using Rust regex?
- How to get a capture group using Rust regex?
- How to escape dots with regex in Rust?
- How to use regex captures in Rust?
- How to get the last element of a slice in Rust?
See more codes...