Create String with String::from()
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
Single char
Convert &str to String
Create String from rust
Empty string
Three chars
Algorithm Flow

Solution Approach
Best Answers
fn solution(s: &str) -> String {
String::from(s)
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
