rust string interpolation

In Rust, string interpolation is achieved using the format! macro or the println! macro. The format! macro allows you to create a formatted string by combining literals and variables, while the println! macro prints the formatted string to the console.

Here's an example of using the format! macro for string interpolation:

let name = "Alice";
let age = 25;
let interpolated_string = format!("My name is {} and I am {} years old", name, age);

In this example, the format! macro is used to create an interpolated string that combines the values of the name and age variables. The resulting string will be "My name is Alice and I am 25 years old".

You can also use positional arguments in string interpolation by specifying the index of the argument in the format string. Here's an example:

let name = "Alice";
let age = 25;
let interpolated_string = format!("{1} is {0} years old", age, name);

In this example, the positions of the variables age and name are swapped, resulting in the string "Alice is 25 years old".

The println! macro works in a similar way to format!, but instead of returning a formatted string, it prints the string to the console. Here's an example:

let name = "Alice";
let age = 25;
println!("My name is {} and I am {} years old", name, age);

When you run this code, it will print "My name is Alice and I am 25 years old" to the console.

That's it! This is how you can perform string interpolation in Rust using the format! and println! macros.