【问题标题】:Rename enum fields in match (rust)重命名匹配中的枚举字段(锈)
【发布时间】:2021-07-14 09:39:56
【问题描述】:

我在枚举上有一个匹配块,其中一个匹配案例在同一个枚举上包含另一个匹配块。像这样的:

fn foo(&mut self, scenario: &mut Scenario) -> Result<&mut Self>
{
match self {
            Scenario::Step { attributes, .. } => {
                match scenario {
                    Scenario::Step { attributes,.. } => {

有什么方法可以访问内部匹配中的两个attributes 字段?我看到了从内部匹配块返回该字段的可能性,但是可以以更美观的方式处理它吗?

【问题讨论】:

    标签: rust enums match


    【解决方案1】:

    你可以像这样重命名匹配的变量:

    fn foo(&mut self, scenario: &mut Scenario) -> Result<&mut Self>
    {
    match self {
                Scenario::Step { attributes: attrs1, .. } => {
                    match scenario {
                        Scenario::Step { attributes: attrs2,.. } => {
                            // do something with attrs1 and attrs2
    

    更好的是,你可以在一个元组中匹配它们:

    fn foo(&mut self, scenario: &mut Scenario) -> Result<&mut Self>
    {
    match (self, scenario) {
                (Scenario::Step { attributes: attrs1, .. }, Scenario::Step { attributes: attrs2,.. }) => {
                    // do something with attrs1 and attrs2
    

    【讨论】:

    • 另外请注意,您不必同时重命名两者,您可以保留一个为 attributes 而无需重命名。
    【解决方案2】:

    你可以在一个元组中同时匹配它们:

    fn foo(&mut self, scenario: &mut Scenario) -> Result<&mut Self> {
        match (self, escenario) {
            (Scenario::Step { attributes, .. }, Scenario::Step { attributes: attributes2, .. }) => {}
        }
    }
    

    【讨论】:

    • 这行不通,因为 Rust 不知道它应该将 attributes 分配给 attributes2。您必须像 Scenario::Step { attributes: attributes2, .. } 一样明确地重命名它
    • @isaactfa,是的,很好,谢谢!
    猜你喜欢
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-19
    • 1970-01-01
    相关资源
    最近更新 更多