CodeBlanks Logo Icon CodeBlanks

Summary - Advanced patterns

Combine struct, @ and guard to build a color classifier.

Advanced pattern matching summary

Patterns filter struct fields by literals and bind them, and unpack nested structures in one go. name @ pattern checks and binds; guards (if) check relations the pattern can't express but don't count toward exhaustiveness. Binding modes: move, ref, ref mut; chosen automatically when matching on a reference. Slice patterns ([first, .., last], [x, rest @ ..]) split arrays and vectors by length.

Slice patterns

Slice patterns combine branching by length and access to the ends in one construct:

fn tanimla(v: &[i32]) -> String {
    match v {
        [] => String::from("boş"),
        [x] => format!("tek: {x}"),
        [ilk, .., son] if ilk == son => format!("uçlar eşit: {ilk}"),
        [ilk, orta @ .., son] => format!("{ilk}..{son} ({} ara)", orta.len()),
    }
}

The set of patterns is exhaustive: empty, single and two-or-more cover every length (even though the guarded arm doesn't count, the last arm takes the rest).

Practice Describe a slice

Write the tanimla function above. Print the results for [], [7], [1, 2, 1] and [1, 2, 3, 4] on separate lines.

Starter code

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

Sample solution

main.rs
fn tanimla(v: &[i32]) -> String {
    match v {
        [] => String::from("boş"),
        [x] => format!("tek: {x}"),
        [ilk, .., son] if ilk == son => format!("uçlar eşit: {ilk}"),
        [ilk, orta @ .., son] => format!("{ilk}..{son} ({} ara)", orta.len()),
    }
}

fn main() {
    let girdiler: [&[i32]; 4] = [&[], &[7], &[1, 2, 1], &[1, 2, 3, 4]];
    for v in girdiler {
        println!("{}", tanimla(v));
    }
}

Expected output

boş
tek: 7
uçlar eşit: 1
1..4 (2 ara)

Questions and answers

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

1 Does the pattern <code>[ilk, .., son]</code> match a single-element slice?

  • Panic
  • It doesn't compile
  • No; at least two elements are needed Correct answer
  • Yes, first and last are the same

Explanation: Two named positions need two separate elements; a single element needs an [x] arm.

2 Bind the middle

Question
[ilk, orta ____ .., son] => format!("{} ara", orta.len()),
Answer
[ilk, orta @ .., son] => format!("{} ara", orta.len()),

Explanation: orta @ .. binds the middle elements as a slice.

3 Slice and result

Term Meaning
[] boş
[7] tek: 7
[1, 2, 1] uçlar eşit: 1
[1, 2, 3, 4] 1..4 (2 ara)

All lessons in Advanced