Bases de Rust

Rust Strings: String vs &str

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

  • Débutant
  • 2 min de lecture
  • 1 exemple exécutable
Ce que vous allez apprendre
  • 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.

Points clés

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

Exemple Rust exécutable

Rust
Exécuter le code →
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}");
    }
}
Obtenir un bouton Run pour cet exemple Résultat de l'exécution
Hello, Rust!
length: 12
upper: HELLO, RUST!
contains Rust: true
Hello
Rust!

S'entraîner

Ouvrez l'exemple dans le compilateur en ligne, modifiez une valeur ou ajoutez une ligne, et devinez la sortie avant de l'exécuter. Cassez ensuite le code exprès et lisez le message du compilateur.

Leçon terminée ?

Marquez-la comme apprise pour suivre votre progression.

Suivante : Reverse a String →

S'entraîner avec un défi

Utilisez le contenu de cette leçon pour résoudre un vrai problème. Chaque défi s'exécute dans le navigateur, avec des tests instantanés et une revue par l'IA.

Tous les défis