Append with push_str()
Write a Rust function that takes two strings (&str) and returns a new String by appending the second string to the first using push_str(). The push_str() method appends a given string slice to the end of a String, growing the String's capacity as needed.
String::push_str() is the standard way to append string data to an existing String. Unlike the + operator which consumes the left operand, push_str() works on a mutable reference (&mut self) and can be called multiple times to build up a string incrementally. This makes it ideal for constructing strings in loops.
The push_str() method is efficient because it can reuse the existing buffer's capacity. If the buffer has enough spare capacity, no reallocation is needed. If not, it reallocates with doubled capacity, making repeated push_str() calls amortized O(1). This growth strategy is shared with Vec::push().
Time complexity is O(m) where m is the length of the appended string, as characters must be copied into the buffer. Space complexity is O(n+m) total for the resulting String. The method does not modify the input string slice.
Edge cases include appending to an empty String, appending an empty string slice (no change), appending strings with special characters or spaces, and ensuring the function returns the concatenated result as a new owned String.
Example Input & Output
Append "def" to "abc"
Append to empty string
Append single char as string
Append empty string does nothing
Append with space
Algorithm Flow

Solution Approach
Best Answers
fn solution(s1: &str, s2: &str) -> String {
let mut result = String::from(s1);
result.push_str(s2);
result
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
