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.
Lo que aprenderás
- 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.
Puntos clave
- &str borrows text stored somewhere else.
- String owns its text and can grow.
- len counts bytes, not characters.
Ejemplo ejecutable de Rust
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}");
}
}
Hello, Rust!
length: 12
upper: HELLO, RUST!
contains Rust: true
Hello
Rust!Practica
Abre el ejemplo en el compilador online, cambia un valor o añade una línea y predice la salida antes de ejecutarlo. Después rompe el código a propósito y lee el mensaje del compilador.
¿Terminaste esta lección?
Márcala como aprendida para seguir tu progreso.
Tu progreso está guardado en este navegador Inicia sesión para conservarlo en todos tus dispositivos.
Practica con un reto
Usa lo que cubre esta lección para resolver un problema real. Cada reto se ejecuta en el navegador, con pruebas al instante y una revisión de IA.
- Contar Vocales Cuenta las vocales en un texto. Fácil
- Initials From a Name Build uppercase initials from a full name. Fácil