Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between .. and _ in Rust?

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?

like image 667
Afsa Avatar asked Sep 03 '25 17:09

Afsa


1 Answers

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(_, _) => {}
    }
}
like image 113
Chayim Friedman Avatar answered Sep 06 '25 10:09

Chayim Friedman