We can concatenate strings with the plus operator (+).
Here is a program that concatenates the strings "I love coding. " and "It is fun!" and assigns the resulted string to a variable message:
let message = String::from("I love coding. ") + "It is fun!";
println!("{}", message);
Output:
I love coding. It is fun!
Concatenation with variables:
String concatenation is redundat when used with string literals because we already know what the resulted string would be.
For example, in our program, we could have initialized message directly with the bigger string instead of doing concatenation:
let message = "I love coding. It is fun!";
println!("{}", message);
String concatenation is used to dynamically generate messages that can be different depending on context.
For example, I might want to print a specific message about my favorite animal, whatever that is:
let favorite_animal = "parrot";
let message = String::from("My favorite animal is the ") + favorite_animal;
println!("{}", message);
Output:
My favorite animal is the parrot
The value of message will differ if my favorite animal was "dog" or "cat", but it would still make sense.
Concatenating multiple strings:
We can concatenate as many strings as we want in the same line of code by adding a + before each string:
let animal = "parrot";
let name = "Andy";
println!("{}", name.to_string() + ", that's a nice " + animal + " you got there!");
Output:
Andy, that's a nice parrot you got there!
Be careful to add whitespaces and other characters you want in your message
Assignment
Follow the Coding Tutorial and let's practice with string concatenation!
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. Premium is unlimited.