41

When iterating over arguments (for example) thats the most straightforward way to skip the first N elements?

eg:

use std::env; fn main() { for arg in env::args() { println!("Argument: {}", arg); } } 

I tried env::args()[1..] but slicing isn't supported.

Whats the simplest way to skip the first arguments of an iterator?

2 Answers 2

67

Turns out the .skip() method can be used, eg:

use std::env; fn main() { for arg in env::args().skip(1) { println!("Argument: {}", arg); } } 
Sign up to request clarification or add additional context in comments.

Comments

4

You could also do something like

 fn main() { let args: Vec<String> = env::args().collect(); for x in &args[1..] { println!("{:?}", x); } } 

2 Comments

Can you add a brief explanation of this solution (and how it compares to other answers)?
The question posted is very specific to iterators and how to skip n elements while using an iterator. This answer collects the iterator into a collection and then slices into it, solves the problem, but not specifically with iterators i.e. without collecting. The top answer is correct and should have been the accepted answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.