< 返回版块

schacker 发表于 2021-11-16 10:11

Tags:rust,match,enum

代码如下

match &*name {
  "assert" | "clear" | "count" | "countReset" | "debug"
  | "dir" | "dirxml" | "error" | "group" | "groupCollapsed"
  | "groupEnd" | "info" | "log" | "table" | "time"
  | "timeEnd" | "timeLog" | "trace" | "warn" => {}
  _ => return,
}

如何优化多的有点臃肿的字符串形式呢?

评论区

写评论
munpf 2021-11-16 14:09

直接用HashSet,然后用contains判断是否包含name就可以了,不过数据量不大,用列表顺序查找判断也可以

作者 schacker 2021-11-16 13:45

这看起来感觉好一点,可复用

--
👇
n2:

const KEYWORDS: &[&str] = &["assert", "clear", "count", "countReset", "debug",
    "dir", "dirxml", "error", "group", "groupCollapsed",
    "groupEnd", "info", "log", "table", "time", "timeEnd", "timeLog", "trace", "warn"];
fn main() {
    let name = "error".to_owned();
    if KEYWORDS.iter().any(|s| s == &name){
        // 你自己的code
    }else{
        return;
    }
}
作者 schacker 2021-11-16 13:43

这其实看起来还是很多的感觉,就是全都在一起的感觉,结构上清晰了一点

--
👇
chinagxwei: ```rust enum Name { Assert, Clear, Count, }

impl Name { pub fn as_str(&self) -> &'static str { return match self { Name::Assert => "Assert", Name::Clear => "Clear", Name::Count => "Count" }; } }



这样能达到你想要的吗?
chinagxwei 2021-11-16 12:32
enum Name {
    Assert,
    Clear,
    Count,
}

impl Name {
    pub fn as_str(&self) -> &'static str {
        return match self {
            Name::Assert => "Assert",
            Name::Clear => "Clear",
            Name::Count => "Count"
        };
    }
}

这样能达到你想要的吗?

n2 2021-11-16 11:25
const KEYWORDS: &[&str] = &["assert", "clear", "count", "countReset", "debug",
    "dir", "dirxml", "error", "group", "groupCollapsed",
    "groupEnd", "info", "log", "table", "time", "timeEnd", "timeLog", "trace", "warn"];
fn main() {
    let name = "error".to_owned();
    if KEYWORDS.iter().any(|s| s == &name){
        // 你自己的code
    }else{
        return;
    }
}
matrikslee 2021-11-16 10:57

将字符串常量丢进一个hashmap,然后用haspmap的find来判断就可以了

1 共 6 条评论, 1 页