You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Rust嵌套枚举中匹配字符串并编写测试?

解决Rust枚举测试中的字符串匹配问题

针对你遇到的matches!宏中无法调用函数的问题,这里有两种简洁的标准库解决方案:

方法一:使用matches!的模式守卫

利用模式绑定结合守卫条件,直接在匹配中判断字符串内容,既简洁又能准确校验:

#[test]
fn is_correct_food() {
    let food = Food::Fruit("Banana".to_string()); // 来自被测函数的结果
    // 绑定Fruit的名字到name变量,同时判断是否等于"Apple"
    assert!(matches!(food, Food::Fruit(name) if name == "Apple"));
}

运行这个测试时,若被测函数返回的是Food::Fruit("Banana".to_string()),断言会失败,符合预期;只有返回Food::Fruit("Apple".to_string())时才会通过。

方法二:解构后用assert_eq!校验

通过if let解构枚举变体,再直接比较字符串,错误信息会更清晰:

#[test]
fn is_correct_food() {
    let food = Food::Fruit("Banana".to_string()); // 来自被测函数的结果
    if let Food::Fruit(name) = food {
        assert_eq!(name, "Apple");
    } else {
        panic!("预期是Fruit类型的食物,实际得到其他类型");
    }
}

这种方式不仅能校验字符串内容,还能同时确保返回的是Fruit变体,若返回Vegitable会直接触发panic,明确告知错误类型。

内容的提问来源于stack exchange,提问作者Nick

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 03:50:26