Program command line arguments String or str

Hello, here is the playground.

Is there a nicer way to do the if block. All I want is to give a &str to the function read_csv(path : &str) ?


fn main() {

    let mut args = std::env::args();
    let program_name : Option<> = args.next();
    let argument1 = args.next();

    println!("{:?} {:?}",program_name, argument1);

// start of ugly code
    let path = if let Some(p) = argument1 {
        p.to_string()
    } else {
        "extract_cleaned.csv".to_string()
    };
// end of ugly code ?
    read_csv(path.as_str());
}

fn read_csv(path : &str) {
 // do something
}

Thank you !

    let path = argument1.as_deref().unwrap_or("extract_cleaned.csv");

    read_csv(path);

Playground

fn main() {
    let mut args = std::env::args();
    let program_name = args.next();
    let argument1 = args.next();

    println!("{:?} {:?}",program_name, argument1);
    let path = argument1.unwrap_or("extract_cleaned.csv".into());
    read_csv(&path);
}

fn read_csv(path : &str) {
 // do something
}

Note that this allocates unnecessarily (because you only want a &str anyways) and unconditionally (because .unwrap_or is used rather than .unwrap_or_else).

1 Like

Oh yes of course !!! I forgot about it ! (may be too late coding isn't good)

Simple and clear thank you @steffahn and @RedDocMD !!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.