Pular para o conteúdo
Nesta página

Correspondência de Padrão e Desestruturação

Expressão Match

match compara um valor contra múltiplos padrões:

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

Tipos de Padrão

Padrões Literais

Corresponder a valores exatos:

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

Também funciona com strings e booleanos:

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

Vinculação de Variável

Vincular o valor correspondido a um nome:

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

Curinga _

Corresponde a qualquer coisa sem vincular:

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

Padrões de Tupla

Desestruturar 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})",
}

Padrões de Struct

Desestruturar structs:

struct Point { x: f64, y: f64 }

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

Padrões de Enum

Desestruturar 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,
}

Padrões Ou |

Corresponder a múltiplos padrões:

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

Cláusulas Guard if

Adicionar condições aos padrões:

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

Padrões Aninhados

Padrões podem ser aninhados 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)
    },
    _ => {},
}

Desestruturação em let

Desestruturação de Tupla

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

Desestruturação de Struct

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

Desestruturação em Loop For

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

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

If Let

Combinar correspondência de padrão com condicionais:

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

Com enums:

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

Encadeado com 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

Loop enquanto um padrão corresponder:

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

Isso é equivalente a:

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

Buscar no Zolo

9 resultados

enespt-br