Saltar al contenido
En esta página

Coincidencia de Patrones y Desestructuración

Expresión Match

match compara un valor contra múltiples patrones:

match value {
    pattern1 => expr1,
    pattern2 => expr2,
    _ => default_expr,
}

Tipos de Patrón

Patrones Literales

Coincidir con valores exactos:

match x {
    0 => "zero",
    1 => "one",
    42 => "the answer",
    _ => "other",
}

También funciona con cadenas y booleanos:

match command {
    "quit" => exit(),
    "help" => show_help(),
    _ => print("unknown command"),
}

Vinculación de Variable

Vincular el valor coincidente a un nombre:

match x {
    n => print("got {n}"),
}

Comodín _

Coincide con cualquier cosa sin vincular:

match result {
    Result::Ok(value) => use(value),
    _ => {},  // ignore errors
}

Patrones de Tupla

Desestructurar tuplas:

let point = (3, 4)

match point {
    (0, 0) => "origin",
    (x, 0) => "on x-axis at {x}",
    (0, y) => "on y-axis at {y}",
    (x, y) => "({x}, {y})",
}

Patrones de Struct

Desestructurar structs:

struct Point { x: f64, y: f64 }

match p {
    Point { x: 0.0, y: 0.0 } => "origin",
    Point { x, y } => "({x}, {y})",
}

Patrones de Enum

Desestructurar variantes de enum:

enum Shape {
    Circle(f64),
    Rectangle(f64, f64),
    Triangle { base: f64, height: f64 },
}

match shape {
    Shape::Circle(r) => 3.14 * r * r,
    Shape::Rectangle(w, h) => w * h,
    Shape::Triangle { base, height } => base * height / 2.0,
}

Patrones O |

Coincidir con múltiples patrones:

match key {
    'w' | 'W' | 'ArrowUp' => move_up(),
    's' | 'S' | 'ArrowDown' => move_down(),
    _ => {},
}

Cláusulas Guard if

Añadir condiciones a los patrones:

match value {
    n if n < 0 => "negative",
    0 => "zero",
    n if n > 100 => "large",
    n => "normal: {n}",
}

Patrones Anidados

Los patrones pueden anidarse arbitrariamente:

match event {
    Event::Click { pos: Point { x, y }, button } if button == "left" => {
        handle_click(x, y)
    },
    Event::Key { code, modifiers: Mods { ctrl: true, .. } } => {
        handle_ctrl_key(code)
    },
    _ => {},
}

Desestructuración en let

Desestructuración de Tupla

let (x, y) = get_position()
let (first, ...rest) = items

Desestructuración de Struct

let Point { x, y } = point
let Point { x: px, y: py } = point  // rename fields

Desestructuración en Bucle For

for (index, value) in list.enumerate() {
    print("{index}: {value}")
}

for (key, val) in map.entries() {
    print("{key} = {val}")
}

If Let

Combinar coincidencia de patrones con condicionales:

if let Some(value) = maybe_value {
    print("Got: {value}")
} else {
    print("Nothing")
}

Con enums:

if let Shape::Circle(radius) = shape {
    print("Circle with radius {radius}")
}

Encadenado con else-if:

if let Result::Ok(data) = fetch_data() {
    process(data)
} else if let Result::Ok(cached) = read_cache() {
    process(cached)
} else {
    print("No data available")
}

While Let

Bucle mientras un patrón coincida:

while let Some(item) = iterator.next() {
    process(item)
}

Esto es equivalente a:

loop {
    match iterator.next() {
        Some(item) => process(item),
        _ => break,
    }
}

Buscar en Zolo

9 resultados

enespt-br