Code Logo

Convert with From Trait

Published at25 Jul 2026
Rust Traits & Generics Easy 0 views
Like0

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 for U automatically provides the reciprocal Into for T, giving both conversion directions for free. The From trait is used throughout the standard library: String::from(&str), Vec::from(&[T]), and many more.

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

Example 1
Input
"Charlie"
Output
Charlie
Explanation

Longer name

Example 2
Input
"Bob"
Output
Bob
Explanation

Another name

Example 3
Input
"Eve"
Output
Eve
Explanation

Short name

Example 4
Input
"Alice"
Output
Alice
Explanation

From<&str> creates Name from string

Example 5
Input
"Diana"
Output
Diana
Explanation

Different name

Algorithm Flow

Recommendation Algorithm Flow for Convert with From Trait
Recommendation Algorithm Flow for Convert with From Trait

Solution Approach

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
}

Best Answers

rust - Approach 1
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
}