What is the difference between .. and _ in Rust?
Asked Answered
A

1

28

What is the difference between two periods and underscore in this case:

 let a = Some("a");
    match a {
        Some(_) => println!("we are in match _"),

        _ => panic!(),
    }
    match a {
        Some(..) => println!("we are in match .."),
        _ => panic!(),
    }

Both do compile and run, but what is the reason to prefer one before another?

Aporia answered 14/6, 2023 at 18:1 Comment(0)
F
33

In this case, there is no difference.

In general, _ ignores one element (field, array element, tuple field etc.) while .. ignores everything left (all fields except those explicitly specified etc.). But since Some contains only one field, this has the same effect.

Here's an example where they differ:

struct Foo(u32, u32);

fn foo(v: Foo) {
    match v {
        Foo(..) => {}
        Foo(_, _) => {}
    }
}
Fevre answered 14/6, 2023 at 18:10 Comment(1)
One reason to prefer the .. form (or even Foo { .. }, which also works even for tuple structs/enum variants) is because it makes the match robust to changes in the number of arguments or whether it uses the braced or tuple style in the declaration. (Or you can prefer the _ form if you want the code to break and require review on any change to the variant.) When you have a whole bunch of variants with a variety of kinds of argument it is convenient to be able to write all the branches the same way.Hotblooded

© 2022 - 2025 — McMap. All rights reserved.