AnyCompiler

Strings e Slices

Um string slice, &str, é uma referência a parte de um String (ou a um inteiro) — ele toma emprestado o texto subjacente em vez de ser seu dono. Fazer slicing com [start..end] te dá uma visão do string original sem copiar seus dados.

fn main() {
    let s = String::from("hello world");

    let hello = &s[0..5];
    let world = &s[6..11];

    println!("{} {}", hello, world);
}
Output
hello world

String vs &str

String é um tipo com ownership, crescível (growable) — você vai vê-lo sempre que uma função precisar construir ou reter texto. &str é uma visão emprestada de um texto que tem ownership em outro lugar, incluindo os literais de string, que são &str por padrão. Funções que só precisam ler um string geralmente recebem &str, já que ele aceita tanto um String (via borrow) quanto um literal.

fn main() {
    let s1: &str = "a string slice";
    let s2: String = String::from("an owned String");

    println!("{}", s1);
    println!("{}", s2);
}
Output
a string slice
an owned String

Próximo: structs — agrupar dados relacionados, e anexar métodos a eles.

Practice Exercise

Dado let s = String::from("rust lang"), crie um slice first que contenha apenas "rust" (os primeiros 4 caracteres), depois imprima first.