OneBite.Dev - Coding blog in a bite size

Combine Two Strings In Rust

Code snippet for how to Combine Two Strings In Rust with sample and detail explanation

Concatenating two strings in Rust is a common task that you’ll come across in most Rust projects. This article provides a simple guide on how to combine two strings in Rust language.

Code snippet to combine two strings in Rust

Here is a simple piece of code demonstrating how to concatenate two strings in Rust:

fn main() {
    let str1 = String::from("Hello ");
    let str2 = String::from("World!");
    let combined_str = str1 + &str2;

    println!("{}", combined_str);
}

On running this code, it prints: Hello World!

Code Explanation for combining two strings in Rust

In the above code snippet, we’re combining two strings “Hello ” and “World!” to produce “Hello World!“. Let’s break it down step by step.

  1. Initialize the first string:
let str1 = String::from("Hello ");

We use String::from("Hello ") to create a new string str1 containing the text “Hello “.

  1. Initialize the second string:
let str2 = String::from("World!");

Again, String::from("World!") is used to create another string str2 with the text “World!“.

  1. Combine the two strings:
let combined_str = str1 + &str2;

You may notice that &str2 is used instead of simply str2. This is because the + operator uses the add method which consumes str1 and requires str2 to be a reference. Therefore, the & operator is used to get a reference from str2.

  1. Print the final combination:
println!("{}", combined_str);

Finally, we print the concatenated string using the println! macro. Thus, Hello World! will be printed as the output.

rust