I'm trying to write a function that processes a sequence of integers.
fn process_one(n: u32) {}
fn process<II>(ii: II)
where
II: IntoIterator<Item = u32>,
{
for n in ii {
process_one(n);
}
}
I want the client to be able to pass a Vec<u32>
without consuming it (process(&v)
). This function can't be used because <&Vec<u32> as IntoIterator>::Item
is &u32
; I'd have to pass v.iter().cloned()
instead, which is annoying.
Alternatively, I could make the bound Item = &u32
and use process_one(*n)
, but then I have the reverse problem.
I'm trying to think of a way to write this generically, but I can't figure out how. As far as I can tell, none of AsRef
, Borrow
, ToOwned
, or Deref
work.
What I need is a way to write this:
fn process<II>(ii: II)
where
II: IntoIterator<Item = MAGIC>, /* MORE MAGIC */
{
for n in ii {
process_one(MAGIC(n));
}
}
so that all of these compile:
fn test() {
let v: Vec<u32> = vec![1, 2, 3, 4];
process(&v);
process(v);
process(1..10);
}
I know I can do this using a custom trait, but I feel like there should be a way without all that boilerplate.