我正在尝试编写一个处理整数序列的函数。
fn process_one(n: u32) {}
fn process<II>(ii: II)
where
II: IntoIterator<Item = u32>,
{
for n in ii {
process_one(n);
}
}
我希望客户端能够传递 Vec<u32>
不消耗它(process(&v)
)。此功能无法使用,因为 <&Vec<u32> as IntoIterator>::Item
是&u32
;我必须通过 v.iter().cloned()
相反,这很烦人。
或者,我可以设置边界 Item = &u32
并使用 process_one(*n)
, 但后来我遇到了相反的问题。
我正在尝试想出一种通用的方式来编写此代码,但我不知道该怎么做。据我所知,AsRef
都没有, Borrow
, ToOwned
, 或 Deref
工作。
我需要的是一种写法:
fn process<II>(ii: II)
where
II: IntoIterator<Item = MAGIC>, /* MORE MAGIC */
{
for n in ii {
process_one(MAGIC(n));
}
}
这样所有这些都可以编译:
fn test() {
let v: Vec<u32> = vec![1, 2, 3, 4];
process(&v);
process(v);
process(1..10);
}
我知道我可以使用自定义特征来做到这一点,但我觉得应该有一种没有所有样板的方法。
最佳答案
Borrow
作品:
use std::borrow::Borrow;
fn main() {
let x = vec![1, 2, 3];
process(x.iter());
process(x);
process(1..3);
}
fn process_one(n: u32) {
println!("{}", n)
}
fn process<I>(iter: I)
where
I: IntoIterator,
I::Item: Borrow<u32>,
{
for x in iter {
process_one(*x.borrow());
}
}
关于generics - 如何编写采用 `u32` 或 `&u32` 的任何迭代器的通用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48317761/