如何将结构中的字符串与常量值匹配? [英] How do I match a String in a struct with a constant value?

查看:39
本文介绍了如何将结构中的字符串与常量值匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用静态 str 值与 Rust 结构中的 String 匹配?这是一个最小的例子:

Is it possible to match against a String in a struct in Rust with a static str value? Here is a minimal example:

struct SomeStruct {
    a: String,
}

fn main() {
    let s = SomeStruct {
        a: "Test".to_string(),
    };
    match s {
        SomeStruct { a: "Test" } => {
            println!("Match");
        }
    }
}

这不会编译,因为静态 str 引用无法与 String 成员匹配.可以在不解构 a 然后在匹配中添加嵌套 if 语句的情况下使其工作吗?

This won't compile because the static str reference can't be matched against the String member. Can it be made to work without destructuring a and then adding a nested if statement in the match?

推荐答案

目前不可能在单一模式中做到这一点,但在某些时候可能会成为可能.目前,用模式和 匹配守卫,像这样:

It is not currently possible to do this in a single pattern, though at some time it is likely to become possible. For now, it’s probably easiest to replace the pattern with a pattern and match guard, like this:

match s {
    SomeStruct { ref a } if a == "Test" => {
        println!("Match");
    }
}

这篇关于如何将结构中的字符串与常量值匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆