Rust has two types to represent strings, both of which will be covered in more depth later. Both always store UTF-8 encoded strings.

  • String - a modifiable, owned string.
  • &str - a read-only string. String literals have this type.
fn main() {
    let greeting: &str = "Greetings";
    let planet: &str = "đŸȘ";
    let mut sentence = String::new();
    sentence.push_str(", ");
    println!("final sentence: {}", sentence);
    println!("{:?}", &sentence[0..5]);
    //println!("{:?}", &sentence[12..13]);
This slide should take about 10 minutes.

This slide introduces strings. Everything here will be covered in more depth later, but this is enough for subsequent slides and exercises to use strings.

  • Invalid UTF-8 in a string is UB, and this not allowed in safe Rust.

  • String is a user-defined type with a constructor (::new()) and methods like s.push_str(..).

  • The & in &str indicates that this is a reference. We will cover references later, so for now just think of &str as a unit meaning “a read-only string”.

  • The commented-out line is indexing into the string by byte position. 12..13 does not end on a character boundary, so the program panics. Adjust it to a range that does, based on the error message.

  • Mit puren Zeichenketten (raw strings) kannst Du einen &str-Wert mit deaktivierten Escape-Zeichen erstellen: r"\n" == "\\\\n". Du kannst doppelte AnfĂŒhrungszeichen einbetten, indem Du auf beiden Seiten der AnfĂŒhrungszeichen die gleiche Anzahl von # verwendest:

    fn main() {
        println!(r#"<a href="link.html">link</a>"#);
        println!("<a href=\"link.html\">link</a>");