rustFormat string at compile time in Rust
Format strings in Rust can be compiled at compile time using the format!
macro. This macro takes a format string as its first argument, followed by any number of arguments that will be used to fill in the format string. The format string can contain placeholders for the arguments, which are denoted by curly braces {}
.
Code example:
let name = "John";
let age = 30;
let message = format!("Hello, my name is {}, and I am {} years old.", name, age);
println!("{}", message);
Output
Hello, my name is John, and I am 30 years old.
Explanation of code parts:
let name = "John";
- This line declares a variablename
and assigns it the value of the stringJohn
.let age = 30;
- This line declares a variableage
and assigns it the value of the integer30
.let message = format!("Hello, my name is {}, and I am {} years old.", name, age);
- This line uses theformat!
macro to create a string with the given format string and arguments. The placeholders{}
are replaced with the values of the variablesname
andage
.println!("{}", message);
- This line prints the value of themessage
variable to the console.
Helpful links:
More of Rust
- How to replace a capture group using Rust regex?
- Regex example to match multiline string in Rust?
- How to parse a file with Rust regex?
- How to use regex lookahead in Rust?
- How to use regex captures in Rust?
- How to use regex to match a group in Rust?
- How to match the end of a line in a Rust regex?
- How to perform matrix operations in Rust?
- How to use regex to match a double quote in Rust?
- How to replace strings using Rust regex?
See more codes...