Convert with From Trait
Write a Rust function that defines a Name struct containing a String field, implements the From<&str> trait to convert a string slice into a Name, and returns the inner string. The From trait provides the .from() method for infallible conversions between types.
The From trait is one of the most important conversion traits in Rust. Implementing From
Using From for conversions is idiomatic Rust. Unlike as casting which is only for primitive types, From works for any types and can perform allocation, copying, or complex transformation. The trait has a single method: fn from(value: T) -> Self. Implementing From signals that the conversion is infallible and semantically meaningful.
Time complexity is O(n) where n is the string length (due to String allocation). Space complexity is O(n) for the new String. The From implementation clones the string data from the &str into an owned String.
Edge cases include empty strings (creates Name with empty String), very long strings, and ensuring the implementation consumes the input &str without modifying it.
Example Input & Output
Longer name
Another name
Short name
From<&str> creates Name from string
Different name
Algorithm Flow
Solution Approach
Implement the From trait to define conversion from one type to another. The From trait provides a standard from() method used by into() for ergonomic type conversion. Implementing From automatically provides Into.
From is the idiomatic way to define conversions in Rust. The standard library provides From implementations for common conversions like String::from("hello") and i32::from(5u8).
Time O(1), Space O(1).
Best Answers
struct Name {
value: String,
}
impl From<&str> for Name {
fn from(s: &str) -> Self {
Name { value: s.to_string() }
}
}
fn solution(s: &str) -> String {
let name = Name::from(s);
name.value
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
