美文网首页
枚举模式与match

枚举模式与match

作者: 简书网abc | 来源:发表于2021-08-22 23:24 被阅读0次

    1,枚举的定义与基本使用

    具体可以参考该文档:
    https://rust.bootcss.com/ch06-01-defining-an-enum.html

    fn main() {
        enum Book {
            Nothing,
            Papery {index: u32},
            Electronic {url: String, price: u32},
        }
    
        let _not = Book::Nothing;
        let _book = Book::Papery {index: 100};
        let _ebook = Book::Electronic {url: String::from("url..."), price: 34};
    
        match _ebook {
            Book::Nothing => {
                println!("nothing");
            },
            Book::Papery { index} => {
                println!("Papery book {}", index);
            },
            Book::Electronic { url, price} => {
                println!("E-book is {}, price = {}", url, price);
            }
        }
    }
    
    

    2, Option枚举类

    如果你想定义一个可以为空值的类,你可以这样:
    let opt = Option::Some("Hello");
    如果你想针对 opt 执行某些操作,你必须先判断它是否是 Option::None:

    fn main() {
        let opt = Option::Some("Hello");
        match opt {
            Option::Some(something) => {
                println!("{}", something);
            },
            Option::None => {
                println!("opt is nothing");
            }
        }
    }
    

    如果你的变量刚开始是空值,你体谅一下编译器,它怎么知道值不为空的时候变量是什么类型的呢?

    所以初始值为空的 Option 必须明确类型:

    fn main() {
        let opt: Option<&str> = Option::None;
        match opt {
            Option::Some(something) => {
                println!("{}", something);
            },
            Option::None => {
                println!("opt is nothing");
            }
        }
    }
    

    或者使用简介写法

    fn main() {
        let t = Some(64);
        match t {
            Some(t) => println!("{}", t),
            _ => println!("No"),
        }
    }
    

    3, if let 语法

    fn main() {
        let i = 0;
        match i {
            0 => println!("zero"),
            _ => {},
        }
    
        let i = 1;
        if let 1 = i {
            println!("zero");
        } else {
            println!("no zero");
        }
    
        enum Book {
            Papery(u32),
            Electronic(String)
        }
        let book = Book::Electronic(String::from("url ... "));
        if let Book::Papery(index) = book {
            println!("Papery {}", index);
        } else if let Book::Electronic(url) = book{
            println!("Electronic url : {}", url);
        } else {
            println!("No thinking");
        }
    }
    
    

    相关文章

      网友评论

          本文标题:枚举模式与match

          本文链接:https://www.haomeiwen.com/subject/kxynbltx.html