如何编写一个需要迭代器的Rust函数? [英] How to write a Rust function that takes an iterator?

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

问题描述

我想编写一个接受迭代器的函数,并返回一些操作的结果。具体来说,我试图迭代 HashMap 的值:

 使用std :: collections :: HashMap; 

fn find_min< a>(vals:Iterator< Item =&'a u32>) - >选项<&'a u32> {
vals.min()
}

fn main(){
let mut map = HashMap :: new();
map.insert(zero,0u32);
map.insert(one,1u32);
println!(Min value {:?},find_min(map.values()));
}

但唉:

< pre class =lang-none prettyprint-override> 错误:无法在特征对象上调用`min`方法
- > src / main.rs:4:10
|
4 | vals.min()
| ^^^

错误[E0277]:特性绑定了`std :: iter :: Iterator< Item =&'a u32> +'static:std :: marker :: Sized`不满足
- > src / main.rs:3:17
|
3 | (vals:Iterator< Item =&'a u32>) - >选项<&'a u32> {
| ^^^^`std :: iter :: Iterator< Item =&'a u32> +'static`在编译时没有一个已知的常量大小
|
= help:特征std :: marker :: Sized没有为`std :: iter :: Iterator< Item =&'a u32>实现+'static`
=注意:所有局部变量必须有一个静态已知大小

错误[E0308]:不匹配类型
- > src / main.rs:11:41
|
11 | println!(Min value {:?},find_min(map.values()));
| ^^^^^^^^^^^^预期trait std :: iter :: Iterator,找到struct std :: collections :: hash_map :: Values`
|
= note:预期的类型`std :: iter :: Iterator< Item =& u32> +'static`
找到类型`std :: collections :: hash_map :: Values<'_& str,u32>`

如果我尝试按引用传递,则会得到相同的错误;如果我使用 Box ,我会遇到生命期错误。

解决方案

您在这里使用泛型:

  fn find_min<'a,I>(vals:I) - >选项<&'a u32> 
其中
I:Iterator< Item =&'a u32>,
{
vals.min()
}

可以通过两种方式使用特征:作为类型参数和特征对象的边界。这本书有一章关于 traits 和关于特质对象的章节,以解释这两个用例。



另外,您经常想要实现 IntoIterator 因为这可以使代码调用你的函数更好:

  fn find_min<'a,I>(vals:I) - > ;选项<&'a u32> 
其中
I:IntoIterator< Item =&'a u32>,
{
vals.into_iter()。min()
}


I'd like to write a function that accepts an iterator and returns the results of some operations on it. Specifically, I'm trying to iterate over the values of a HashMap:

use std::collections::HashMap;

fn find_min<'a>(vals: Iterator<Item=&'a u32>) -> Option<&'a u32> {
    vals.min()
}

fn main() {
    let mut map = HashMap::new();
    map.insert("zero", 0u32);
    map.insert("one", 1u32);
    println!("Min value {:?}", find_min(map.values()));
}

But alas:

error: the `min` method cannot be invoked on a trait object
 --> src/main.rs:4:10
  |
4 |     vals.min()
  |          ^^^

error[E0277]: the trait bound `std::iter::Iterator<Item=&'a u32> + 'static: std::marker::Sized` is not satisfied
 --> src/main.rs:3:17
  |
3 | fn find_min<'a>(vals: Iterator<Item = &'a u32>) -> Option<&'a u32> {
  |                 ^^^^ `std::iter::Iterator<Item=&'a u32> + 'static` does not have a constant size known at compile-time
  |
  = help: the trait `std::marker::Sized` is not implemented for `std::iter::Iterator<Item=&'a u32> + 'static`
  = note: all local variables must have a statically known size

error[E0308]: mismatched types
  --> src/main.rs:11:41
   |
11 |     println!("Min value {:?}", find_min(map.values()));
   |                                         ^^^^^^^^^^^^ expected trait std::iter::Iterator, found struct `std::collections::hash_map::Values`
   |
   = note: expected type `std::iter::Iterator<Item=&u32> + 'static`
              found type `std::collections::hash_map::Values<'_, &str, u32>`

I get the same error if I try to pass by reference; if I use a Box, I get lifetime errors.

解决方案

You want to use generics here:

fn find_min<'a, I>(vals: I) -> Option<&'a u32>
where
    I: Iterator<Item = &'a u32>,
{
    vals.min()
}

Traits can be used in two ways: as bounds on type parameters and as trait objects. The book The Rust Programming Language has a chapter on traits and a chapter on trait objects that explain these two use cases.

Additionally, you often want to take something that implements IntoIterator as this can make the code calling your function nicer:

fn find_min<'a, I>(vals: I) -> Option<&'a u32>
where
    I: IntoIterator<Item = &'a u32>,
{
    vals.into_iter().min()
}

这篇关于如何编写一个需要迭代器的Rust函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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