1

我有这样的掌声App

let m = App::new("test")
    .arg(
        Arg::with_name("INPUT")
            .help("a string to be frobbed")
            .multiple(true),
    )
    .get_matches();

如果有的话,我想将参数作为字符串的可迭代读取,myapp str1 str2 str3但如果没有,则充当过滤器并从 stdin 读取可迭代的行cat afile | myapp。这是我的尝试:

let stdin = io::stdin();
let strings: Box<Iterator<Item = String>> = if m.is_present("INPUT") {
    Box::new(m.values_of("INPUT").unwrap().map(|ln| ln.to_string()))
} else {
    Box::new(stdin.lock().lines().map(|ln| ln.unwrap()))
};

for string in strings {
    frob(string)
}

我相信,因为我只需要Iterator特征,所以 aBox<Iterator<Item = String>>是唯一的方法。那是对的吗?

4

1 回答 1

2

很少有“唯一的出路”,这种情况也不例外。一种替代方法是使用静态分派而不是动态分派。

您的主要处理代码需要一个字符串迭代器作为输入。所以你可以像这样定义一个处理函数:

fn process<I: IntoIterator<Item = String>>(strings: I) {
    for string in strings {
        frob(string);
    }
}

此代码的调用可能如下所示:

match m.values_of("INPUT") {
    Some(values) => process(values.map(|ln| ln.to_string())),
    None => process(io::stdin().lock().lines().map(|ln| ln.unwrap())),
}

编译器将发出两个不同版本的process(),每个迭代器类型一个。每个版本都静态调用为其编译的迭代器函数,并且只有一次分派到match语句中的正确函数。

(我可能在这里弄错了一些细节,但你明白了。)

另一方面,您的版本使用 type Box<dyn Iterator<Item = String>>,因此迭代器将在堆上分配,并且每次next()在迭代器上调用时都会有一个动态调度。这可能没问题。

当然还有更多的方式来构建代码并在两种不同类型的输入之间进行分派,例如使用 crate 中的Either类型either,或者简单地为这两种情况编写两个不同for的循环。选择哪一个取决于与代码的其他要求、性能要求和个人偏好的权衡。

于 2019-03-13T20:45:30.187 回答