rustHow can I use sprintf with a Rust string?
You can use sprintf
with a Rust string by using the format!
macro. This macro takes a format string and a list of arguments, and returns a String
object.
Example code
let name = "John";
let age = 30;
let message = format!("{} is {} years old", name, age);
println!("{}", message);
Output example
John is 30 years old
Code explanation
let name = "John";
: This declares a variablename
and assigns it the value"John"
.let age = 30;
: This declares a variableage
and assigns it the value30
.let message = format!("{} is {} years old", name, age);
: This uses theformat!
macro to create aString
object with the format string"{} is {} years old"
and the argumentsname
andage
.println!("{}", message);
: This prints theString
objectmessage
to the console.
Helpful links
More of Rust
- How to get a capture group using Rust regex?
- How to convert the keys of a Rust HashMap to a vector?
- How to match whitespace with a regex in Rust?
- How to convert a Rust HashMap to a BTreeMap?
- How to match the end of a line in a Rust regex?
- How to replace a capture group using Rust regex?
- How to parse JSON string in Rust?
- How to use a HashBrown with a Rust HashMap?
- How to match a URL with a regex in Rust?
- How to replace all matches using Rust regex?
See more codes...