英文:
Comprehensive Rust Ch.16.2 - pattern matching for structs using capture and const expressions
问题
在Pattern Matching - Destructuring structs Comprehensive Rust by Google 的第二个讲演者备注点的理解上有困难。
以下是示例代码:
struct Foo {
x: (u32, u32),
y: u32,
}
#[rustfmt::skip]
fn main() {
let foo = Foo { x: (1, 2), y: 3 };
match foo {
Foo { x: (1, b), y } => println!("x.0 = 1, b = {b}, y = {y}"),
Foo { y: 2, x: i } => println!("y = 2, x = {i:?}"),
Foo { y, .. } => println!("y = {y}, other fields were ignored"),
}
}
以下是相关备注内容:
捕获和常量表达式之间的区别可能很难察觉。尝试将第二个分支中的2更改为一个变量,并看看它微妙地不起作用。将其更改为常量,然后看到它再次工作。
它试图说什么呢?当将y: 2
中的2
替换为类似y: a
之类的内容时,是否仍然可以编译通过?
英文:
Having trouble understanding the second speaker note point in the Pattern Matching - Destructuring structs of the Comprehensive Rust by Google.
Here is the sample code.
struct Foo {
x: (u32, u32),
y: u32,
}
#[rustfmt::skip]
fn main() {
let foo = Foo { x: (1, 2), y: 3 };
match foo {
Foo { x: (1, b), y } => println!("x.0 = 1, b = {b}, y = {y}"),
Foo { y: 2, x: i } => println!("y = 2, x = {i:?}"),
Foo { y, .. } => println!("y = {y}, other fields were ignored"),
}
}
And the note in question.
> The distinction between a capture and a constant expression can be hard to spot. Try changing the 2 in the second arm to a variable, and see that it subtly doesn’t work. Change it to a const and see it working again.
Thinking my English is bad, but what is it trying to say when it says to observe that it "subtly doesn't work" when the change is made? Substituting the 2
in y: 2
with something like y: a
should still compile?
答案1
得分: 5
这意味着执行以下操作:
fn main() {
let foo = Foo { x: (1, 2), y: 3 };
let a = 2;
match foo {
Foo { x: (1, b), y } => println!("x.0 = 1, b = {b}, y = {y}"),
Foo { y: a, x: i } => println!("y = 2, x = {i:?}"),
Foo { y, .. } => println!("y = {y}, 其他字段被忽略"),
}
}
并期望它具有匹配 y
是否为2的相同效果,但实际上它将匹配任何 y
并捕获 y
到 a
(遮蔽 a = 2
)。
英文:
It means doing:
fn main() {
let foo = Foo { x: (1, 2), y: 3 };
let a = 2;
match foo {
Foo { x: (1, b), y } => println!("x.0 = 1, b = {b}, y = {y}"),
Foo { y: a, x: i } => println!("y = 2, x = {i:?}"),
Foo { y, .. } => println!("y = {y}, other fields were ignored"),
}
}
And expecting it to have the same effect of matching if y
is 2, but actually it will match for any y
and capture the y
in a
(shadowing a = 2
).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论