To append a string to another string in Rust, you can use the format!
macro or the push_str
method of the String
type.
In this example,
str1
with a value of "Hello"
.format!
macro to append the string " World"
to str1
.format!
macro concatenates the two strings and returns a new string.fn main() {
let str1 = String::from("Hello");
let concatenated = format!("{} World", str1);
println!("{}", concatenated);
}
Hello World
In this example,
mut str2
with a value of "banana"
.push_str
method to append the string "apple"
to str2
.push_str
method concatenates the two strings and modifies the original str2
.fn main() {
let mut str2 = String::from("banana");
str2.push_str("apple");
println!("{}", str2);
}
bananaapple
In this tutorial, we learned How to Append a String to another String in Rust language with well detailed examples.