Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rust: Why not Into<String> for &str?

Consider this statement: From<T> for U implies Into<U> for T. source

let t="abc"; and note that t has type &str

Everyone has used: let s=String::from(t);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So that we have: From<&str> for String

According to the implication above we have:Into<String> for &str

However, the following does not work:

fn main(){
    let z="abc";
    let x = String::from(z);
    let s=&str::into(x);
}

What am I not understanding?

>Solution :

It works, except that &str::into(z) is understood as &(str::into(z)). If you want to call the associated function into for type &str, you must use a qualified name for that type:

fn main(){
    let z = "abc";
    let x = String::from(z);
    let s: String = <&str>::into(x);
}

Note that the type annotation String was added because otherwise Rust cannot know which type is the target of into.

Otherwise, you can also use the method syntax

    let s: String = x.into();

or the associated function of trait Into:

    let s: String = Into::into(x);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading