[rust-016] 关于rust的match语法问题

参考文档:https://doc.rust-lang.org/book/ch06-03-if-let.html

match,类似switch,根据一个对象的值决定执行哪个分支。

在语法糖层面稍微有点差别:c语言的switch case,case只是执行若干语句,如果要返回一个值,用return返回; match的执行部分,必须是表示式,表达式结尾没有分号,如果加了分号,是语句,可以在表示式之前写若干条语句。

enum Coin{
    No1,
    No2,
    No3,
    No4
}

fn test_retrun(x:Coin) -> i32{
    match x{
        Coin::No1 => {
            println!("No1");
            1 //注意,这里没有分号,有分号是语句会报错,类型不匹配,没有分号则是表达式
        }
        Coin::No2 => 2,
        Coin::No3 => 3,
        Coin::No4 => 4,
    }
}


fn main(){
    let x = Coin::No1;
    println!("return v = {}", test_retrun(x));
}

match的所有分支,=>运算符后面是返回值,返回值的类型要一致,否则会报错,下面这种可以运行:

enum Coin{
    No1,
    No2,
    No3,
}

fn test_retrun(x:Coin) -> i32{
    match x{
        Coin::No1 => {
            println!("No1");
            println!("ok 1");
        }
        Coin::No2 => {
            println!("No2");
            println!("ok 2");
        }
        Coin::No3 => {
            println!("No3");
            println!("ok 3");
        }
    }
    1
}


fn main(){
    let x = Coin::No1;
    println!("return v = {}", test_retrun(x));
}

但这种就不能运行:

enum Coin{
    No1,
    No2,
    No3,
}

fn test_retrun(x:Coin) -> i32{
    match x{
        Coin::No1 => {
            println!("No1");
            println!("ok 1");
        }
        Coin::No2 => {
            println!("No2");
            println!("ok 2");
        }
        Coin::No3 => {
            println!("No3");
            3
        }
    }
    1
}


fn main(){
    let x = Coin::No1;
    println!("return v = {}", test_retrun(x));
}


//报错信息如下:
/*
/home/xx/.cargo/bin/cargo run --color=always --bin xx
   Compiling xx v0.1.0 (/home/xx/tmp/untitled)
error[E0308]: mismatched types
  --> src/main.rs:19:13
   |
8  | /     match x{
9  | |         Coin::No1 => {
10 | |             println!("No1");
11 | |             println!("ok 1");
...  |
19 | |             3
   | |             ^ expected `()`, found integer
20 | |         }
21 | |     }
   | |     -- help: consider using a semicolon here
   | |_____|
   |       expected this to be `()`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0308`.
error: could not compile `xx`.

To learn more, run the command again with --verbose.

Process finished with exit code 101

*/

"_"匹配任何值,类似SQL的"*"

fn main(){
    let some_u8_value = 0u8;
    match some_u8_value {
        1 => println!("one"),
        3 => println!("three"),
        5 => println!("five"),
        7 => println!("seven"),
        _ => (),
    }
}

也可以用if let省略掉"_",不过说实话if let这个表达不够好,可能会导致一些理解上的问题:

#[derive(Debug)]
enum UsState {
    Alabama,
    Alaska,
}

enum Coin {
    Penny,
    Nickel,
    Dime,
    Quarter(UsState),
}

fn main() {
    let coin = Coin::Penny;
    let mut count = 0;
    if let Coin::Quarter(state) = coin {
        println!("State quarter from {:?}!", state);
    } else {
        count += 1;
    }

    println!("count = {}", count)
}



或者

fn main() {
    let favorite_color: Option<&str> = None;
    let is_tuesday = false;
    let age: Result<u8, _> = "34".parse();

    if let Some(color) = favorite_color {
        println!("Using your favorite color, {}, as the background", color);
    } else if is_tuesday {
        println!("Tuesday is green day!");
    } else if let Ok(age) = age {
        if age > 30 {
            println!("Using purple as the background color");
        } else {
            println!("Using orange as the background color");
        }
    } else {
        println!("Using blue as the background color");
    }
}

或者

fn main(){
    let mut stack = Vec::new();

    stack.push(1);
    stack.push(2);
    stack.push(3);

    while let Some(top) = stack.pop() {
        println!("{}", top);
    }
}

matach还有一种在循环里的用法

fn main(){
    let xs = [1,2,3,4,5];
    for x in &xs{
        let xx = match x{
            1 => "is 1",
            _ => continue,
        };
        println!("x = {}", x);
        println!("xx = {}", xx)
    }
}

/*
运行结果
x = 1
xx = is 1
*/

这个continue,是不违反语法的,只是不知道做何解。如果把continue换成println!("not 1")会报错,换成break,不报错。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值