CodeBlanks Logo Icon CodeBlanks

_ wildcard

Catch all remaining cases in one arm with _.

The _ wildcard

match must be exhaustive: every possible value must fit an arm. For types with many values such as integers, _ collects the rest. _ doesn't bind the value; if you want to bind it, use a name (diger => ..):

fn gun_turu(g: u8) -> &'static str {
    match g {
        1..=5 => "hafta içi",
        6 | 7 => "hafta sonu",
        _ => "geçersiz",
    }
}

Ignoring parts

_ is used inside patterns too: (_, y) ignores the first element, Some(_) ignores the content. .. skips several parts:

let sayilar = (2, 4, 8, 16, 32);
let (ilk, .., son) = sayilar;
println!("{ilk} {son}");   // 2 32

let _kullanilmayan = 5;   // a name starting with _ gives no warning

_x binds the value but silences the "unused variable" warning; a lone _ doesn't bind at all.

Practice Day type

Write the function fn gun_turu(g: u8) -> &'static str above. Print the results for 3, 7 and 9 on one line separated by |.

Starter code

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

Sample solution

main.rs
fn gun_turu(g: u8) -> &'static str {
    match g {
        1..=5 => "hafta içi",
        6 | 7 => "hafta sonu",
        _ => "geçersiz",
    }
}

fn main() {
    println!("{}|{}|{}", gun_turu(3), gun_turu(7), gun_turu(9));
}

Expected output

hafta içi|hafta sonu|geçersiz

Questions and answers

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

1 Why doesn't <code>match g { 1..=5 =&gt; .., 6 | 7 =&gt; .. }</code> (g: u8) compile?

  • It compiles
  • The values 0 and 8..=255 aren't covered Correct answer
  • | can't be used
  • The range is wrong

Explanation: The compiler lists the missing values: "patterns `0_u8` and `8_u8..=u8::MAX` not covered".

2 Catch the rest

Question
match g {
    1..=5 => "hafta içi",
    6 | 7 => "hafta sonu",
    ____ => "geçersiz",
}
Answer
match g {
    1..=5 => "hafta içi",
    6 | 7 => "hafta sonu",
    _ => "geçersiz",
}

Explanation: _ catches every value that didn't fit the earlier arms.

3 Pattern and effect

Term Meaning
_ Fits anything, doesn't bind
_x Binds, no warning
(ilk, .., son) Skips the middle
Some(_) Ignores the content

All lessons in Beginner