How can I concatenate strings in Rust?

Asked about 2 months ago Viewed 7 times

How can I perform string concatenation with &str String, and the various combinations you can make with them (&str and &str, String and String, etc.) in Rust?

0
J
J Early User
109
1 Answer
Sort by
Posted about 2 months ago

In Rust there are several different ways to concatenate strings depending on whether you're working with &str, String, or a combination of both.

+ Operator

In the context of string concatenation, the + operator takes ownership of the left-hand String and appends the borrowed right-hand &str.

let a = String::from("Hello, ");
let b = "world!";
let result = a + b;

println!("{}", result); // "Hello, world!"
// Note: `a` is moved and can’t be used afterward

If you have two Strings and want to use + concatenation, you'll need to provide a reference to the string you want to append as the right hand.

let a = String::from("Hello, ");
let b = String::from("world!");
let result = a + &b;

push_str for Mutable Strings

If you have mutable access to a String, you can append to it directly with push_str. This changes the contents of the String.

let mut s = String::from("Hello");
s.push_str(", world");
s.push('!'); // .push is for characters only

println!("{}", s); // "Hello, world!"

format! Macro

When you need to join more than two strings or want to avoid moving ownership, use format!.

let a = "Hello";
let b = String::from(", ");
let c = "world!";
let result = format!("{}{}{}", a, b, c);

println!("{}", result); // "Hello, world!"
// No variables are moved – all can be reused

In summary, with the + operator or push_str, you will need to own the string you are appending to (meaning you may have to perform an allocation via to_string or other if you don't already own it). format! is more flexible and useful when you want to avoid taking ownership, or are performing multiple/complex concatenations.

0
s
69

Your Answer

You Must Log In or Sign Up to Answer Questions