Rust 枚举及其变体的使用


fn main(){
println!("===============enum=====================");
    enum_test();
}

#[derive(Debug)]
enum In_enum{
    Boy,
    Gril
}
//枚举及其各种变体的使用
#[derive(Debug)]
enum my_enum<'a>{
    A,
    B{b:String,c:i32},//结构体
    C(i32,i32,i32),//元组
    D(Vec<&'a str>), //元组包含向量
    E([i32;5]),      //数组 定义一个数组时,使用;来区分前面的类型以及后面的数量
    F(In_enum),
}

fn enum_test(){
    let A = my_enum::A;
    let B = my_enum::B{b:"Hello Rust".to_string(),c:32};
    let C = my_enum::C(60,32,64);
    let D = my_enum::D(vec!["a","b","c","d"]);
    let E = my_enum::E([0i32;5]);       //实例化多个相同元素的数组时也使用;来区分前面的元素实例及后面的具体数量
    let F = my_enum::F(In_enum::Boy);
    println!(">>>>>>>>>>>>>>>>>>>>");
    println!("{:#?}\n>>>>\n{:#?}\n>>>>\n{:#?}\n>>>>\n{:#?}\n>>>>\n{:#?}\n>>>>\n{:#?}\n>>>>\n",A,B,C,D,E,F);
    let v:Vec<&str> =  match D{
        my_enum::D(v) =>v,
        _ =>vec![],
    };
    println!("{:#?}",v);
}

输出结果为:

===============enum=====================
>>>>>>>>>>>>>>>>>>>>
A
>>>>
B {
    b: "Hello Rust",
    c: 32,
}
>>>>
C(
    60,
    32,
    64,
)
>>>>
D(
    [
        "a",
        "b",
        "c",
        "d",
    ],
)
>>>>
E(
    [
        0,
        0,
        0,
        0,
        0,
    ],
)
>>>>
F(
    Boy,
)
>>>>

[
    "a",
    "b",
    "c",
    "d",
]

你可能感兴趣的:(Rust,笔记)