Rust 如何手动创建 std::env::Args 迭代器进行测试

GG1*_*991 1 rust

我想测试一个采用std::env::Args迭代器作为参数但不使用命令行并使用以下参数提供参数的函数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());
}
Run Code Online (Sandbox Code Playgroud)

cdh*_*wie 6

让你的函数是通用的,并采取任何实现IntoIterator其项目是String值的东西。这将允许您传入任何可以转换为 an Iteratorof 的内容String(包括 anIterator本身)。

这个特性是由Args(本身实现Iterator)和由实现的Vec<String>

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

游乐场