Code Logo

Create String with String::from()

Published at25 Jul 2026
Rust String Handling Easy 0 views
Like0

Write a Rust function that takes a string slice (&str) and returns an owned String using String::from(). The from() method converts a &str into a String by allocating memory on the heap and copying the characters into it.

Rust distinguishes between string slices (&str) which are borrowed views into string data, and Strings which are owned heap-allocated strings. The String::from() method creates a new String by copying the data from the &str. This is the standard way to convert between the two types when you need ownership of the string data.

The from() method is a trait implementation of the From trait. Rust uses From for infallible conversions between types. String::from(&str) is one of the most common conversions in Rust, used whenever a function needs to return an owned string or store string data in a struct. The conversion does not modify the original &str.

Time complexity is O(n) where n is the length of the string slice, as the characters must be copied from the &str to the new String allocation. Space complexity is O(n) for the new heap allocation.

Edge cases include empty string slices (creates an empty String with zero capacity but still heap-allocated), single-character strings, and ensuring the function works correctly with Unicode characters that may be multi-byte.

Example Input & Output

Example 1
Input
"x"
Output
"x"
Explanation

Single char

Example 2
Input
"hello"
Output
"hello"
Explanation

Convert &str to String

Example 3
Input
"rust"
Output
"rust"
Explanation

Create String from rust

Example 4
Input
""
Output
""
Explanation

Empty string

Example 5
Input
"abc"
Output
"abc"
Explanation

Three chars

Algorithm Flow

Recommendation Algorithm Flow for Create String with String::from()
Recommendation Algorithm Flow for Create String with String::from()

Solution Approach

fn solution(s: &str) -> String {
    String::from(s)
}

Best Answers

rust - Approach 1
fn solution(s: &str) -> String {
    String::from(s)
}