CodeBlanks Logo Icon CodeBlanks

Struct patterns

Destructure struct fields with patterns.

Struct patterns

Patterns can both unpack struct fields and match them against specific values. Fields with literal values act as filters, named fields bind; .. ignores the rest:

struct Nokta { x: i32, y: i32 }

fn konum(p: &Nokta) -> String {
    match p {
        Nokta { x: 0, y } => format!("y ekseninde {y}"),
        Nokta { x, y: 0 } => format!("x ekseninde {x}"),
        Nokta { x, y } => format!("düzlemde ({x}, {y})"),
    }
}

If the field name and variable name match, the shorthand is used; for a different name write Nokta { x: yatay, .. }.

Matching through a reference

In match p, p is a &Nokta but the patterns are written as Nokta { .. }. Thanks to "match ergonomics", the compiler adapts the pattern to the reference automatically, and the bound x, y variables become &i32. Comparing with literals (x: 0) still works.

let noktalar = [Nokta { x: 0, y: 3 }, Nokta { x: 2, y: 0 }];
for p in &noktalar {
    println!("{}", konum(p));
}

Practice Classify positions

Write the Nokta struct above and the konum function. Print the results for the points (0, 3), (2, 0) and (1, 1) on separate lines.

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
struct Nokta {
    x: i32,
    y: i32,
}

fn konum(p: &Nokta) -> String {
    match p {
        Nokta { x: 0, y } => format!("y ekseninde {y}"),
        Nokta { x, y: 0 } => format!("x ekseninde {x}"),
        Nokta { x, y } => format!("düzlemde ({x}, {y})"),
    }
}

fn main() {
    let noktalar = [Nokta { x: 0, y: 3 }, Nokta { x: 2, y: 0 }, Nokta { x: 1, y: 1 }];
    for p in &noktalar {
        println!("{}", konum(p));
    }
}

Expected output

y ekseninde 3
x ekseninde 2
düzlemde (1, 1)

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which arm does <code>Nokta { x: 0, y: 0 }</code> take in the match above?

  • The second arm
  • The third arm
  • None
  • The first arm: "y ekseninde 0" Correct answer

Explanation: Arms are tried in order; x: 0 satisfies the first arm, so it stops there. If you want a separate arm for the origin, write it at the top.

2 Match a literal, bind the rest

Question
match p {
    Nokta { x: ____, y } => format!("y ekseninde {y}"),
    _ => String::new(),
}
Answer
match p {
    Nokta { x: 0, y } => format!("y ekseninde {y}"),
    _ => String::new(),
}

Explanation: x: 0 matches only if x is zero; the value of y is bound.

3 Point and result

Term Meaning
Nokta { x: 0, y: 3 } y ekseninde 3
Nokta { x: 2, y: 0 } x ekseninde 2
Nokta { x: 1, y: 1 } düzlemde (1, 1)
Nokta { x: 0, y: 0 } y ekseninde 0

All lessons in Advanced