0

What is the most idiomatic way to match against an iterator's item? For example, if we take command line arguments, what is the best way to use pattern matching on one of the items? This is what I'm doing and I'm not 100% sure why as_ref() is required and why &args[0] wouldn't work:

let args: Vec<String> = env::args().skip(1).collect();
match args[0].as_ref() {...}
ljedrz
  • 20,316
  • 4
  • 69
  • 97
Ali
  • 7,297
  • 2
  • 19
  • 19
  • Since matching against strings was already answered in the past (e.g. [How to match a String against string literals in Rust?](https://stackoverflow.com/questions/25383488/how-to-match-a-string-against-string-literals-in-rust)), I suggest to tackle matching against program's arguments or, more generally, an iterator's item. – ljedrz Dec 04 '17 at 20:10
  • thanks, that link is where I actually learned about as_ref(). I used it and it works well but was just confused about why u need to call the method on that index. – Ali Dec 04 '17 at 20:14
  • 1
    You need `as_ref()` so that the `String` in the pattern is treated as a `&str` string slice and can be matched against slices in the `match` body. – ljedrz Dec 04 '17 at 20:19

1 Answers1

2

Since env::args() returns an iterator (Args), you can work with it like with any other iterator. If you want to match against a given item once, the simplest way to do it would be:

use std::env;

fn main() {
    let mut args = env::args().skip(1);

    match args.next() {
        Some(x) => {
            if &x == "herp derp" { ... }
        },
        None => ()
    }
}
ljedrz
  • 20,316
  • 4
  • 69
  • 97
  • @AliYazdani I modified the answer to *actually* match against the argument's value now :). – ljedrz Dec 04 '17 at 20:31
  • beauty! thanks. lol "herp derp". One more question (if u want to answer), I was using Vec initially because I thought args need to be allocated to the heap since size wont be known until runtime. What is the mechanism that makes your version work without being explicit with the compiler on data requirements? – Ali Dec 04 '17 at 21:03
  • 1
    @AliYazdani the argument strings are still located on the heap; it's just that they don't need to be collected into a `Vec` for it to be possible to use them. – ljedrz Dec 04 '17 at 21:05