0x0me
0x0me

Reputation: 754

Read input in pattern match branch

My program should read some parameters from the command line. If someone does not provide an optional password parameter the program should ask for it. Therefore the corresponding field is modeled as an Option type.

This works well if the parameter is provided from the command line ( option having the value of Some("..."), but the branch matching the None case does not ask for input.

The simplified program looks like

fn main() {
    use std::io::{self,Read};

    let arg : Option<String> = None; // Does not terminate
    //let arg : Option<String> = Some("Some arg".to_string()); // works well printing 'Some arg'
    println!("Checking for password");


    let password = match arg {
        Some(val) => val.to_string(),
        None => {
            print!("Password:");
         let mut buffer = String::new();
         io::stdin().read_to_string(&mut buffer).unwrap();
         buffer
        }
    };

    println!("password is {}", password);
}

Running the program preinitialized with Some("Some arg") prints the string "password is Some arg" to the console as expected, but switching to the None does nothing, even not terminating the program.

Could you spot my mistake or give me some advice? I am using rustc verison rustc 1.4.0 (8ab8581f6 2015-10-27). Thanks in advance.

Upvotes: 0

Views: 61

Answers (1)

antoyo
antoyo

Reputation: 11933

You need to use read_line():

fn main() {
    use std::io::{self,Read};

    let arg : Option<String> = None; // Does not terminate
    //let arg : Option<String> = Some("Some arg".to_string()); // works well printing 'Some arg'
    println!("Checking for password");

    let password = match arg {
        Some(val) => val.to_string(),
        None => {
            print!("Password:");
            let mut buffer = String::new();
            io::stdin().read_line(&mut buffer).unwrap();
            buffer
        }
    };

    println!("password is {}", password);
}

The read_to_string() function reads until end of file. Your program does indeed read input, but you need to send it the EOF character (Ctrl-D on Linux) for it to continue executing.

Upvotes: 2

Related Questions