Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

From and Into for String and &str

  • &str

  • String

  • from

  • into

  • We can create a String from an &str by using the String::from() method because String implements the From trait for &str.

  • We can also use the into method, but then we must tell Rust the expected type.

  • For some reason we cannot use the Turbofish syntax.

fn main() {
    let a = "Hello World!";
    println!("{a}");

    let b = String::from(a);
    println!("{b}");

    let c: String = a.into();
    println!("{c}");

    // let d = a.into::<String>();
    // method takes 0 generic arguments but 1 generic argument was supplied
    // println!("{d}");

    let e = Into::<String>::into(a);
    println!("{e}");
}