create a template string in rust

To create a template string in Rust, you can use the format! macro. The format! macro allows you to create a formatted string by specifying the format string and the values to be inserted into the string. Here's an example:

main.rs
let name = "John";
let age = 30;
let message = format!("My name is {} and I am {} years old.", name, age);
println!("{}", message);
132 chars
5 lines

Output:

main.rs
My name is John and I am 30 years old.
39 chars
2 lines

In the example above, we define a name variable with the value "John", an age variable with the value 30, and a message variable that uses the format! macro to create a string that contains the name and age variables in the specified format. The println! macro is then used to print the message variable to the console.

You can also concatenate multiple strings using the + operator:

main.rs
let first_name = "John";
let last_name = "Doe";
let full_name = first_name.to_string() + " " + last_name;
println!("{}", full_name);
133 chars
5 lines

Output:

main.rs
John Doe
9 chars
2 lines

In the example above, we define a first_name variable with the value "John", a last_name variable with the value "Doe", and a full_name variable that concatenates the first_name and last_name strings using the + operator. The println! macro is then used to print the full_name variable to the console.

gistlibby LogSnag