将地图与矢量结合使用 [英] Using map with Vectors
问题描述
尽管向量最适合过程式编程,但我想对它们使用 map
函数.以下代码段有效:
Although vectors are best suited for procedural programming, I would like to use a map
function on them. The following snippet works:
fn map<A, B>(u: &Vec<A>, f: &Fn(&A) -> B) -> Vec<B> {
let mut res: Vec<B> = Vec::with_capacity(u.len());
for x in u.iter() {
res.push(f(x));
}
res
}
fn f(x: &i32) -> i32 {
*x + 1
}
fn main() {
let u = vec![1, 2, 3];
let v = map(&u, &f);
println!("{} {} {}", v[0], v[1], v[2]);
}
为什么标准库中没有这样的函数?(也在 std::collections::LinkedList
中).有没有别的办法处理?
Why isn't there any such function in the standard library? (and also in std::collections::LinkedList
). Is there another way to deal with it?
推荐答案
Rust 喜欢比这更通用;映射是通过迭代器完成的,而不是仅仅通过向量或切片.
Rust likes to be more general than that; mapping is done over iterators, rather than over solely vectors or slices.
几个演示:
let u = vec![1, 2, 3];
let v: Vec<_> = u.iter().map(f).collect();
let u = vec![1, 2, 3];
let v = u.iter().map(|&x| x + 1).collect::<Vec<_>>();
.collect()
可能是其中最神奇的部分,它允许您将迭代器的所有元素收集到各种不同的类型中,如 FromIterator
的实现器.例如,一个T
的迭代器可以收集到Vec
,char
的迭代器可以收集到一个String
, of (K, V)
配对到 HashMap
,依此类推.
.collect()
is probably the most magic part of it, and allows you to collect all the elements of the iterator into a large variety of different types, as shown by the implementors of FromIterator
. For example, an iterator of T
s can be collected to Vec<T>
, of char
s can be collected to a String
, of (K, V)
pairs to a HashMap<K, V>
, and so forth.
这种使用迭代器的方式也意味着您通常甚至不需要在其他语言或其他技术中创建中间向量;这更有效,而且通常同样自然.
This way of working with iterators also means that you often won’t even need to create intermediate vectors where in other languages or with other techniques you would; this is more efficient and typically just as natural.
这篇关于将地图与矢量结合使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!