How do I access a variable outside of an `if let` expression?

后端 未结 3 515
忘掉有多难
忘掉有多难 2020-12-21 15:13

I\'m trying to access command line arguments. If the argument exists, do something, if not, do nothing. I have this code:

fn main() {
    if let Some(a) = st         


        
3条回答
  •  温柔的废话
    2020-12-21 16:02

    I agree that you should either do whatever you want to do inside the if-else blocks. If you just to not indent your code and your else block is small, you can inverse your if-condition.

    Instead of

    let arg = std::env::args().nth(2);
    if let Some(a) = arg {
        let b = a;
        // do stuff
    } else {
        // do other stuff
    }
    

    you can do this

    let arg = std::env::args().nth(2);
    if arg.is_none() {
        // do other stuff
    }
    let b = arg.unwrap();
    // do stuff
    

    If you want the variable to be available in the outer scope, but assign it a value in an inner scope, you can declare it outside.

    let arg = std::env::args().nth(2);
    let a; // declared but not assigned
    if let Some(b) = arg {
        a = b; // wasn't mut but first assignment can be done here
    } else {
        a = "Foobar".to_string();
    }
    println!("{}", a); // available here but was assigned the value inside if
    

提交回复
热议问题