簡體   English   中英

比較Rust中的嵌套枚舉變量

[英]Compare nested enum variants in Rust

學習Rust我碰巧需要比較嵌套枚舉內的變量。 考慮以下枚舉,如何比較實例化的BuffTurget實際變體?

enum Attribute {
  Strength,
  Agility,
  Intellect,
}

enum Parameter {
    Health,
    Mana,
}

enum BuffTarget {
    Attribute(Attribute),
    Parameter(Parameter),
}

在網絡上搜尋導致我有“區別”, 尤其是這樣的比較功能:

fn variant_eq<T>(a: &T, b: &T) -> bool {
    std::mem::discriminant(a) == std::mem::discriminant(b)
}

不幸的是,此功能在我的情況下不起作用:

#[test]
fn variant_check_is_working() {
    let str = BuffTarget::Attribute(Attribute::Strength);
    let int = BuffTarget::Attribute(Attribute::Intellect);
    assert_eq!(variant_eq(&str, &int), false);
}

// Output:

// thread 'tests::variant_check' panicked at 'assertion failed: `(left == right)`
// left: `true`,
// right: `false`', src/lib.rs:11:9

理想情況下,我希望我的代碼像這樣,使用if let

let type_1 = get_variant(BuffTarget::Attribute(Attribute::Strength));
let type_2 = get_variant(BuffTarget::Attribute(Attribute::Intellect));

if let type_1 = type_2 {  
    println!("Damn it!") 
} else { println!("Success!!!") }

此答案中找到了合適的解決方案。 使用#[derive(PartialEq)]枚舉將它們與==進行比較: enum_1 == enum_2

#[derive(PartialEq)]
enum Attribute {
  Strength,
  Agility,
  Intellect,
}

#[derive(PartialEq)]
enum Parameter {
    Health,
    Mana,
}

#[derive(PartialEq)]
enum BuffTarget {
    Attribute(Attribute),
    Parameter(Parameter),
}

let type_1 = BuffTarget::Attribute(Attribute::Strength));
let type_2 = BuffTarget::Attribute(Attribute::Intellect));

assert_eq!((type_1 == type_2), false);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM