Fundamentos de Rust

Rust if, else if and else

Run code only when a condition is true, and use if as an expression that returns a value.

  • Principiante
  • 2 min de lectura
  • 1 ejemplo ejecutable
Lo que aprenderás
  • if, else if, else
  • Conditions must be bool
  • if as an expression
score = 87
  1. 1score >= 90false, skip
  2. 2score >= 70true
  3. 3"Good"this branch runs

The first true branch runs

An if statement runs a block only when its condition is true. The condition must be a bool: Rust does not treat numbers as true or false.

The conditions are checked from top to bottom and only the first true branch runs, so 87 prints Good. Because if is an expression, it can produce a value for let: every branch must then return the same type.

Puntos clave

  1. Conditions are checked from top to bottom.
  2. Only the first true branch runs.
  3. let grade = if ... { 'A' } else { 'B' }; stores the result.

Ejemplo ejecutable de Rust

Rust
Ejecutar código →
main.rs
fn main() {
    let score = 87;

    if score >= 90 {
        println!("Excellent");
    } else if score >= 70 {
        println!("Good");
    } else {
        println!("Keep practicing");
    }

    let grade = if score >= 90 { 'A' } else if score >= 80 { 'B' } else { 'C' };
    println!("Grade: {grade}");
}
Obtén un botón Run para este ejemplo Resultado de ejecutar el código
Good
Grade: B

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: FizzBuzz →

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