Corde

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(greeting);
    sentence.push_str(", ");
    sentence.push_str(planet);
    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.

  • Le stringhe non elaborate (raw) consentono di creare un valore &str con i caratteri di escape disabilitati: r"\n" == "\\n". Puoi racchiudere le doppie virgolette usando una quantità uguale di # su entrambi i lati delle virgolette:

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