Comprehensive Rust Ch.16.2 – 使用捕获和常量表达式进行结构体的模式匹配

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

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 并捕获 ya(遮蔽 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).

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

发表评论

匿名网友

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

确定