Understanding scope and shadowing matches

前端 未结 1 1446
慢半拍i
慢半拍i 2021-01-20 04:06

I\'m trying to improve on the final guessing game sample code a bit. Particularly, I plan to output \"Please input a number!\" if the user does not input a number rather tha

相关标签:
1条回答
  • 2021-01-20 04:47

    Let's look at a simpler reproduction:

    fn make_guess() -> u32 {
        let guess;
    
        {
            let mut guess;
            guess = 1;
        }
    
        guess
    }
    

    Here, you create an outer variable guess and then shadow it inside the block. When you assign the value 1 to guess, you are assigning to the inner variable. The outer variable is never set to anything, thus you end up with the "use of possibly uninitialized variable" error.

    Is there any way to only use one variable

    Indirectly, yes. I'd extract the code to a function. When you have a successful guess, you can simply return. Otherwise you allow the loop to occur:

    fn make_guess() -> u32 {
        loop {
            let mut guess = String::new();
            io::stdin().read_line(&mut guess)
                .ok()
                .expect("Failed to read line");
    
            match guess.trim().parse() {
                Ok(num) => return num,
                Err(_) => {
                    println!("Please input a number!");
                }
            }
        }
    }
    

    This avoids the shadowing completely, avoids having to use an explicit continue, and adds a small amount of abstraction and organization to your code.

    0 讨论(0)
提交回复
热议问题