Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a generic function taking any iterator of `u32` or `&u32`?

Tags:

generics

rust

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.

like image 389
Sebastian Redl Avatar asked Dec 19 '22 01:12

Sebastian Redl


1 Answers

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());
    }
}
like image 171
raggy Avatar answered Jan 04 '23 23:01

raggy