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

Create a String

  • println!

  • String

  • from

  • to_string

  • to_owned

  • The first one is a reference to a string embedded in the program. We can only chnage this in the editor. Not while the program is running.

  • String::from can create a "real" string from an embedded string. This is also what we get from any input. (STDIN, ARGS, file, network etc.)

  • to_string is the method to stringify any value. It works here as well, but we can be clearer with to_owned.

  • to_owned convert a reference to an owned string. More about ownership later.

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

    let text_2 = String::from("Hello World!");
    println!("{text_2}");

    let text_3 = "Hello World!".to_string();
    println!("{text_3}");

    let text_4 = "Hello World!".to_owned();
    println!("{text_4}");

    assert_eq!(text_1, "Hello World!");
    assert_eq!(text_1, text_2);
}

{% embed include file="src/examples/strings/create/out.out)