rustCustom string format in Rust
Rust provides a powerful formatting system for strings, called format!
. It allows you to create strings with dynamic content, and is used in a similar way to println!
.
Here is an example of using format!
to create a string with dynamic content:
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 variable calledname
and assigns it the value of "John".let age = 30;
- This line declares a variable calledage
and assigns it the value of 30.let message = format!("Hello, my name is {}, and I am {} years old.", name, age);
- This line uses theformat!
macro to create a string with dynamic content. The{}
symbols are placeholders for the values of thename
andage
variables.println!("{}", message);
- This line prints themessage
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...