Fondamenti di Rust

Rust Strings: String vs &str

Rust has two string types. Learn when to use each, and how to grow, search and split text.

  • Principiante
  • 2 min di lettura
  • 1 esempio eseguibile
Cosa imparerai
  • String and &str
  • push_str and push
  • contains, split, len
Two string types
&str
  • a borrowed view
  • fixed size
  • "Hello"
String
  • owns its text
  • can grow
  • String::from("Hello")

An owned string and a borrowed view

Rust has two main string types. &str is a view of text stored somewhere else, such as a literal in your code. String owns its text and can grow.

String::from copies the literal into a String that the program owns, so push_str and push can add to it. len counts bytes, not characters. split returns the parts between the separator, one at a time.

Punti chiave

  1. &str borrows text stored somewhere else.
  2. String owns its text and can grow.
  3. len counts bytes, not characters.

Esempio Rust eseguibile

Rust
Esegui il codice →
main.rs
fn main() {
    let greeting = "Hello"; // &str: a borrowed string slice
    let mut message = String::from(greeting); // String: owned and growable
    message.push_str(", Rust");
    message.push('!');

    println!("{message}");
    println!("length: {}", message.len());
    println!("upper: {}", message.to_uppercase());
    println!("contains Rust: {}", message.contains("Rust"));

    for word in message.split(", ") {
        println!("{word}");
    }
}
Crea un pulsante Run per questo esempio Risultato dell'esecuzione
Hello, Rust!
length: 12
upper: HELLO, RUST!
contains Rust: true
Hello
Rust!

Esercitati

Apri l'esempio nel compilatore online, cambia un valore o aggiungi una riga e prova a prevedere l'output prima di eseguirlo. Poi rompi il codice di proposito e leggi il messaggio del compilatore.

Hai finito questa lezione?

Segnala come imparata per tenere traccia dei tuoi progressi.

Prossima: Reverse a String →

Esercitati con una sfida

Usa ciò che questa lezione spiega per risolvere un problema reale. Ogni sfida gira nel browser, con test immediati e una revisione dell'IA.

Tutte le sfide