如何编写一个采用`u32`或`& u32`的迭代器的泛型函数? [英] How to write a generic function taking any iterator of `u32` or `&u32`?

查看:65
本文介绍了如何编写一个采用`u32`或`& u32`的迭代器的泛型函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个处理整数序列的函数.

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);
    }
}

我希望客户端能够通过Vec<u32>而不消耗它(process(&v)).由于<&Vec<u32> as IntoIterator>::Item&u32,因此无法使用此功能;我必须通过v.iter().cloned(),这很烦人.

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.

或者,我可以制作绑定的Item = &u32并使用process_one(*n),但是然后我遇到了相反的问题.

Alternatively, I could make the bound Item = &u32 and use process_one(*n), but then I have the reverse problem.

我正在尝试一种通用的编写方法,但是我不知道该怎么做.据我所知,AsRefBorrowToOwnedDeref均不起作用.

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 有效:

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());
    }
}

这篇关于如何编写一个采用`u32`或`&amp; u32`的迭代器的泛型函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆