Code Logo

Append with push_str()

Published at25 Jul 2026
Rust String Handling Easy 0 views
Like0

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

Example 1
Input
"abc","def"
Output
"abcdef"
Explanation

Append "def" to "abc"

Example 2
Input
"","test"
Output
"test"
Explanation

Append to empty string

Example 3
Input
"x","y"
Output
"xy"
Explanation

Append single char as string

Example 4
Input
"abc",""
Output
"abc"
Explanation

Append empty string does nothing

Example 5
Input
"hello"," world"
Output
"hello world"
Explanation

Append with space

Algorithm Flow

Recommendation Algorithm Flow for Append with push_str()
Recommendation Algorithm Flow for Append with push_str()

Solution Approach

fn solution(s1: &str, s2: &str) -> String {
    let mut result = String::from(s1);
    result.push_str(s2);
    result
}

Best Answers

rust - Approach 1
fn solution(s1: &str, s2: &str) -> String {
    let mut result = String::from(s1);
    result.push_str(s2);
    result
}