rustHow to format string slice in Rust
String slices in Rust can be formatted using the format! macro. This macro takes a format string and a list of arguments and returns a String object. The format string can contain placeholders for the arguments, which are then replaced with the corresponding values.
Code example:
let name = "John";
let age = 30;
let formatted_string = format!("My name is {}, and I am {} years old.", name, age);
Output
My name is John, and I am 30 years old.
Explanation of code parts:
let name = "John";- This line declares a variablenameand assigns it the value"John", which is a string literal.let age = 30;- This line declares a variableageand assigns it the value30, which is an integer literal.let formatted_string = format!("My name is {}, and I am {} years old.", name, age);- This line uses theformat!macro to create aStringobject from the format string"My name is {}, and I am {} years old."and the variablesnameandage. The placeholders{}in the format string are replaced with the values of the variablesnameandage.
Helpful links:
More of Rust
- How to use regex captures in Rust?
- How to replace a capture group using Rust regex?
- How to replace strings using Rust regex?
- How to use non-capturing groups in Rust regex?
- How to print a Rust HashMap?
- How to convert a Rust HashMap to JSON?
- How to use a tuple as a key in a Rust HashMap?
- How to declare a constant Rust HashMap?
- How to split a string with Rust regex?
- Regex example to match multiline string in Rust?
See more codes...