Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

More idiomatic retrieval of command-line args #5

Open
skade opened this issue Oct 26, 2016 · 1 comment
Open

More idiomatic retrieval of command-line args #5

skade opened this issue Oct 26, 2016 · 1 comment

Comments

@skade
Copy link
Contributor

skade commented Oct 26, 2016

The current slides use this code:

fn main() {
    let args: Vec<String> = env::args().collect();

    if args.len() > 1 {
        println!("{}", match read_file(args[1].clone()) {
            Ok(content) => content,
            Err(reason) => panic!(reason) 
        });
    }
}

This does unnecessary bounds checking and an allocation of the command line args.

env::args() is an iterator and already provides positional and crash-safe access to command line arguments:

fn main() {
    let mut args = std::env::args();

    println!("{}", args.len());
    if let Some(file) = args.nth(1) {
        println!("{}", file);
    }
}

I think it would be better to use this. I'm also confused about the clone-call after args[1], is it related to args[1] returning a reference as opposed to the exact value?

@skade skade changed the title More idiomatic retrievel of command-line args More idiomatic retrieval of command-line args Oct 26, 2016
@chikoski
Copy link
Owner

chikoski commented Nov 1, 2016

Thanks. The suggested code look like written in more Rust way. I will update my material with it. Also add a explanation of if let, which is a prerequisite to understand this code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants