Fundamentos de Rust

Rust Variables, mut, const and Shadowing

Variables in Rust cannot change unless you ask. Learn let, let mut, const and shadowing.

  • Principiante
  • 2 min de lectura
  • 1 ejemplo ejecutable
Lo que aprenderás
  • let and let mut
  • Constants with const
  • Shadowing a variable
Declaration → what it allows
let language = "Rust"cannot change
let mut score = 10can change
const MAX_SCORE: u32 = 100fixed for the whole program
let score = score * 2 → a new variable, 30

Immutable by default

Variables in Rust cannot change unless you say so. let creates a variable, let mut creates one you can change, and const creates a value that is fixed for the whole program.

score is declared with mut, so score += 5 is allowed. The second let score creates a new variable with the same name, which is called shadowing. The braces in println! print the variables named inside them.

Puntos clave

  1. let creates a variable that cannot change.
  2. let mut allows the value to change.
  3. A second let with the same name creates a new variable (shadowing).

Ejemplo ejecutable de Rust

Rust
Ejecutar código →
main.rs
fn main() {
    let language = "Rust";
    let mut score = 10;
    score += 5;

    const MAX_SCORE: u32 = 100;
    let score = score * 2; // shadowing creates a new variable

    println!("{language}: {score} of {MAX_SCORE}");
}
Obtén un botón Run para este ejemplo Resultado de ejecutar el código
Rust: 30 of 100

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.

Siguiente: Data Types →

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.

Todos los retos