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.
Borrow
works:
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());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With