Why can Into<String> accept String type?

Viewed 398
struct Person {
    name: String,
}

impl Person {
    fn new<S: Into<String>>(name: S) -> Person {
        Person { name: name.into() }
    }
}

fn main() {
    let person = Person::new("test");
    let person = Person::new("test".to_string());
}

&str has Into<String> trait, so I understand that I can call Person::new("test") proprely.

However, I think that Person::new("test".to_string()) fails because String does not have From<String> for String, so Into<String> is not derived automatically.
Why can I call Person::new("test".to_string())?

In addtion, I can call the following code too.

let test: String = String::from("test".to_string());

In the above case, I cannot understand that I can call String::from("test".to_string()) successfully even if String does not have From<String> for String.

1 Answers

However, I think that Person::new("test".to_string()) fails because String does not have From<String> forString, so Into` is not derived automatically.

Actually, From (and thus Into) is reflexive:

// https://doc.rust-lang.org/src/core/convert/mod.rs.html#545-549

impl<T> From<T> for T {
    fn from(t: T) -> T {
        t
    }
}
Related