Fundamentos 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.

  • Iniciante
  • 2 min de leitura
  • 1 exemplo executável
O que você vai aprender
  • 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.

Pontos-chave

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

Exemplo executável de Rust

Rust
Executar código →
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}");
    }
}
Gerar um botão Run para este exemplo Resultado da execução
Hello, Rust!
length: 12
upper: HELLO, RUST!
contains Rust: true
Hello
Rust!

Pratique

Abra o exemplo no compilador online, mude um valor ou adicione uma linha e tente prever a saída antes de executar. Depois quebre o código de propósito e leia a mensagem do compilador.

Terminou esta lição?

Marque como aprendida para acompanhar seu progresso.

Próxima: Reverse a String →

Pratique com um desafio

Use o conteúdo desta lição para resolver um problema real. Cada desafio roda no navegador, com testes instantâneos e uma revisão por IA.

Todos os desafios