Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rust how do I create manually an std::env::Args iterator for testing

Tags:

rust

I would like to test a function that takes a std::env::Args iterator as argument but without using the command line and providing the arguments with a Vec:

use std::env;

fn main() {
    let v = vec!["hello".to_string(), "world".to_string()];
    print_iterator(env::args()); // with the command line
    print_iterator( ??? ); // how should I do with v?
}

fn print_iterator(mut args: env::Args) {
    println!("{:?}", args.next());
    println!("{:?}", args.next());
}
like image 875
gagiuntoli Avatar asked Dec 19 '25 02:12

gagiuntoli


1 Answers

Have your function be generic and take anything implementing IntoIterator whose items are String values. This will let you pass in anything that can be converted into an Iterator of Strings (including an Iterator itself).

This trait is implemented both by Args (itself implementing Iterator) and by Vec<String>.

fn print_iterator(args: impl IntoIterator<Item=String>) {
    let mut iter = args.into_iter();
    println!("{:?}", iter.next());
    println!("{:?}", iter.next());
}

(Playground)

like image 50
cdhowie Avatar answered Dec 20 '25 20:12

cdhowie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!