我想在这里使用 assert_eq!,但编译器告诉我:错误:预期的表达式,找到`}`-->src/lib.rs:18:64|18 |assert_eq!(return_with_fields(), MyEnum::WithFields {..});|^ 预期表达这类似于 为什么在将类似结构的枚举变体与字段进行模式匹配时会出现错误?,但该解决方案不适用于我的情况.当然,我可以使用 match 并自己做,但是能够使用 assert_eq! 会少一些工作. 解决方案 如果您使用的是 Rust 1.42 及更高版本,请参阅 Shepmaster 的回答如下.这里的一个简单解决方案是做相反的断言:assert!(return_with_fields() != MyEnum::WithoutFields);或者更简单:assert_ne!(return_with_fields(), MyEnum::WithoutFields);当然,如果枚举中有更多成员,则必须添加更多断言以涵盖所有可能的情况.或者,这就是 OP 可能想到的,因为 assert! 只是在失败的情况下恐慌,测试可以使用模式匹配并直接调用 panic!如果出现问题:匹配 return_with_fields() {MyEnum::WithFields {..} =>{},MyEnum::WithoutFields =>恐慌!(预期有字段,得到无字段"),}I'd like to check enums with fields in tests while ignoring the actual value of the fields for now.Consider the following example:enum MyEnum { WithoutFields, WithFields { field: String },}fn return_with_fields() -> MyEnum { MyEnum::WithFields { field: "some string".into(), }}#[cfg(test)]mod tests { use super::*; #[test] fn example() { assert_eq!(return_with_fields(), MyEnum::WithFields {..}); }}playgroundI'd like to use assert_eq! here, but the compiler tells me:error: expected expression, found `}` --> src/lib.rs:18:64 |18 | assert_eq!(return_with_fields(), MyEnum::WithFields {..}); | ^ expected expressionThis is similar to Why do I get an error when pattern matching a struct-like enum variant with fields?, but the solution does not apply in my case.Of course, I can use match and do it myself, but being able to use assert_eq! would be less work. 解决方案 If you are using Rust 1.42 and later, see Shepmaster's answer below.A simple solution here would be to do the opposite assertion:assert!(return_with_fields() != MyEnum::WithoutFields);or even more simply:assert_ne!(return_with_fields(), MyEnum::WithoutFields);Of course if you have more members in your enum, you'll have to add more asserts to cover all possible cases.Alternatively, and this what OP probably had in mind, since assert! just panics in case of failure, the test can use pattern matching and call panic! directly in case something is wrong:match return_with_fields() { MyEnum::WithFields {..} => {}, MyEnum::WithoutFields => panic!("expected WithFields, got WithoutFields"),} 这篇关于如果我不关心它的字段,我如何断言枚举是一个特定的变体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-14 18:56