英文:
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(_, _) => {}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论