rustHow to format const string in Rust
Rust provides a number of ways to format const strings. The most common way is to use the format!
macro. This macro takes a format string and a list of arguments and returns a String
object.
Code example:
let name = "John";
let age = 30;
let formatted_string = format!("My name is {}, and I am {} years old.", name, age);
println!("{}", formatted_string);
Output
My name is John, and I am 30 years old.
Explanation:
- The
format!
macro takes a format string and a list of arguments and returns aString
object. - The format string is a string literal that contains placeholders for the arguments. The placeholders are surrounded by curly braces
{}
. - The arguments are passed after the format string and are separated by commas.
- The
println!
macro is used to print the formatted string to the console.
Helpful links:
More of Rust
- How to get a capture group using Rust regex?
- How to use Unicode in a regex in Rust?
- How to get the last element of a Rust slice?
- How to match the end of a line in a Rust regex?
- How to replace a capture group using Rust regex?
- How to use non-capturing groups in Rust regex?
- How to use an enum in a Rust HashMap?
- How to match whitespace with a regex in Rust?
- How to split a string with Rust regex?
- How to match a URL with a regex in Rust?
See more codes...