“在Rust中,..和_有什么区别?”

huangapple go评论74阅读模式
英文:

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

问题

两个句点 "Some(..)" 和下划线 "_" 在这种情况下有什么区别呢?在编译和运行时,两者都可以正常工作,但为什么要在一个情况下选择其中一个而不是另一个呢?

英文:

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?

答案1

得分: 31

在这种情况下,没有区别。

通常情况下,_ 忽略一个元素(字段、数组元素、元组字段等),而 .. 忽略剩下的所有内容(除了明确指定的字段之外的所有字段等)。但由于 Some 只包含一个字段,所以效果相同。

下面是一个它们不同的示例:

struct Foo(u32, u32);

fn foo(v: Foo) {
    match v {
        Foo(..) => {}
        Foo(_, _) => {}
    }
}
英文:

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(_, _) => {}
    }
}

huangapple
  • 本文由 发表于 2023年6月15日 02:01:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76476380.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定