Concatenate A String In Rust
Code snippet for how to Concatenate A String In Rust with sample and detail explanation
The Rust programming language is known for its systems level performance, focus on safety and its great support for concurrent programming. This article aims to guide you through one of Rust’s primary string operation - concatenation.
Code snippet for String Concatenation in Rust
fn main() {
let str1 = "Hello".to_string();
let str2 = ", World!".to_string();
let result = [str1, str2].concat();
println!("{}", result); //This will print "Hello, World!"
}
Code Explanation for String Concatenation in Rust
The Rust programming language handles Strings a little different than other mainstream languages. Though it is general knowledge that Strings are sequence of characters, Rust handles them as an array of bytes.
Let’s break down the code as per usual:
First, two strings are declared by using let
keyword:
The let str1 = "Hello".to_string();
and let str2 = ", World!".to_string();
are just initializing two strings str1 and str2 with values “Hello” and ”, World!” respectively. The to_string()
method converts the literal into a String object.
Next is the actual concatenation:
let result = [str1, str2].concat();
is the line where the actual concatenation happens. The [str1, str2].concat();
statement is an example of an array literal in Rust, where str1 and str2 are the elements. Concat() is called on the array, which concatenates the String elements (str1 and str2 in this case) into a single String.
Finally, we print the result:
The println!("{}", result);
statement prints the concatenated String “Hello, World!“.
By understanding how to handle basic string operations, like concatenation, you are on your way to tackle more complex Rust operations. This is just a small example of the power of Rust and how it suits to handle complex and concurrent system level programming.