'Rust how do I create manually an std::env::Args iterator for testing
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());
}
Solution 1:[1]
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());
}
Solution 2:[2]
Just rewriting the solution of @cdhowie with the format that I have seen in the Rust book. Not sure if this is more idiomatic or not.
fn print_iterator<T>(args: T)
where T: IntoIterator<Item=String> {
let mut iter = args.into_iter();
println!("{:?}", iter.next());
println!("{:?}", iter.next());
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | gagiuntoli |
