Rust:如何匹配枚举和结构,并在匹配时获取枚举值

i7uaboj4  于 2022-12-23  发布在  其他
关注(0)|答案(1)|浏览(148)

这个场景是一个有很多结构体的枚举,Rust如何匹配使用的枚举,并使用枚举结构体值调用适当的函数?
下面是对该场景的一个小重构:

#[derive(Clone)]
pub enum MyEnum {
    ChoiceA(DetailA),
    ChoiceB(DetailB),
}

#[derive(Clone)]
pub struct DetailA {
    pub message: String,
}

#[derive(Clone)]
pub struct DetailB {
    pub password: String,
    pub value: u8,
}

pub fn handleChoiceA(input:DetailA){
    println!("Choice A {}", input.message);
}
pub fn handleChoiceB(input:DetailB){
    println!("Choice B {}", input.password);
}

fn main() {
    let value = MyEnum::ChoiceA({
        DetailA {
            message: "Test".to_string()
        }
    });
    
    match value {
        MyEnum::ChoiceA(_) => { // <---- issue
            handleChoiceA(_);   // <---- issue
        }
        MyEnum::ChoiceB(_) => {
            handleChoiceB(_);
        }
    }
}

以下是指向Rust Playground的链接
一种尝试是尝试使用Rust destruction模式进行匹配,但是我丢失了传递给函数MyEnum::ChoiceA({..})的值,但这样我就没有什么可以传递给handleChoiceA(????)了。
匹配和访问枚举的结构值的正确模式是什么?

hc2pp10m

hc2pp10m1#

像这样?

#[derive(Clone)]
pub enum MyEnum {
    ChoiceA(DetailA),
    ChoiceB(DetailB),
}

#[derive(Clone)]
pub struct DetailA {
    pub message: String,
}

#[derive(Clone)]
pub struct DetailB {
    pub password: String,
    pub value: u8,
}

pub fn handleChoiceA(input: DetailA) {
    println!("Choice A {}", input.message);
}
pub fn handleChoiceB(input: DetailB) {
    println!("Choice B {}", input.password);
}

fn main() {
    let value = MyEnum::ChoiceA({
        DetailA {
            message: "Test".to_string(),
        }
    });

    match value {
        MyEnum::ChoiceA(a) => {
            handleChoiceA(a);
        }
        MyEnum::ChoiceB(b) => {
            handleChoiceB(b);
        }
    }
}
Choice A Test

相关问题