AnyCompiler

Strings y Slices

Un string slice, &str, es una referencia a parte de un String (o a uno completo) — toma prestado el texto subyacente en vez de ser su dueño. Hacer slicing con [start..end] te da una vista del string original sin copiar sus datos.

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 es un tipo con ownership, creciente (growable) — lo verás cada vez que una función necesite construir o retener texto. &str es una vista prestada de un texto que tiene ownership en otro lugar, incluyendo los literales de string, que son &str por defecto. Las funciones que solo necesitan leer un string normalmente toman &str, ya que acepta tanto un String (mediante un borrow) como un 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

Siguiente: structs — agrupar datos relacionados, y adjuntarles métodos.

Practice Exercise

Dado let s = String::from("rust lang"), crea un slice first que contenga solo "rust" (los primeros 4 caracteres), luego imprime first.