如何使用生成器函数初始化 Rust 向量? [英] How to init a Rust vector with a generator function?
问题描述
在语言之间切换可能会很痛苦.一种语言的习语感觉很好",人们开始在其他语言中寻找相同的习语.
Hopping between languages can be painful. Idioms of one language "feel good" and one starts to look for the same idioms in other languages.
在 F# 中,有一种方法可以借助生成器函数来初始化数组.Array.init n 生成器
.现在,我跳到 Rust 了一段时间,我想知道是否有类似的设施,或者我是否必须为自己创建这样的设施.
In F#, there is a way to init an array with the help of a generator function. Array.init n generator
. Now, that I hopped to Rust for a little while, I wonder if there is a similar facility in place or if I have to create myself such a facility.
学习 关于向量的 Rust 标准库文档,我可以找不到与我要查找的内容类似的内容.
Studying Rust standard library documentation about vectors, I could not find anything similar to what I am looking for.
// Looking for something similar to:
Vec<T>::init(n : usize, generator : F) -> Vec<T>
where F: Fn(usize) -> T {
// ...
}
也许它在 Rust 中的工作方式不同,通过迭代器.但我必须承认,Rust 迭代器(以及它们的无数种风格)在我的头脑中仍然有点模糊.
Maybe it works differently in Rust, by means of iterators. But I must admit, that Rust iterators (and their myriads of flavors) are still a tad foggy to my simple mind.
推荐答案
您可以将 range
与 map
一起使用,然后收集结果.
You can use a range
withing a map
and then collect the results.
就像在 F#
文档的示例中一样:
Like in the example for F#
docs:
let my_vector : Vec<i32> = (1..11).map(|x| x*x).collect();
检查这个游乐场
这篇关于如何使用生成器函数初始化 Rust 向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!