如何生成一个包含Rust中所有整数的列表?我正在寻找与Haskell的[n..m]
或Python的range(n, m+1)
相当的版本,但什么都找不到.
我知道int::range
函数,并认为它是我正在寻找的,但它是为了在一个范围内迭代,而不是生成它.
如何生成一个包含Rust中所有整数的列表?我正在寻找与Haskell的[n..m]
或Python的range(n, m+1)
相当的版本,但什么都找不到.
我知道int::range
函数,并认为它是我正在寻找的,但它是为了在一个范围内迭代,而不是生成它.
Note该答案适用于1.0版之前的Rust,不适用于1.0版.被移除了
std::iter::range
个,特别是std::iter::range_inclusive
个.
对于Rust 1.0.0-alpha,实现这一点的最简单方法是使用模块std::iter
:range
和range_inclusive
中提供的便利函数,它们返回迭代器,分别生成[low,high]或[low,high]范围内的数字列表.
此外,可以使用collect
方法从迭代器构建向量:
use std::iter::range_inclusive;
let first_hundred: Vec<i32> = range_inclusive(1, 100).collect();
println!("upper bound inclusive: {:?}, exclusive: {:?}",
first_hundred,
range(101, 201).collect::<Vec<_>>());
请注意,返回值collect
的类型在上述两种用法中都有明确指定.通常,Rust编译器可以在没有明确规范的情况下推断表达式的类型,但collect
是最常见的无法完全推断类型的情况之一,在这种情况下,因为它无法推断实现trait FromIterator<A>
的具体类型,即返回类型collect
.
The type of a generic return value can be specified either as an explicit type in a let
definition statement or inline by using the function::<Type>()
syntax. Since inference fails only due to not knowing a concrete type implementing FromIterator<A>
, it's possible, when explicitly specifying a generic type, to leave "holes" for type arguments which will be inferred, signified by _
. This is done with the second call to collect
above—in the expression Vec<_>
, it's explicitly specified that the container receiving elements from collect
is a Vec<T>
, but the compiler figures out what exact type T
must be. Currently, integers whose types are left unspecified and can't be inferred fall back to i32
(32-bit machine integer) as a default.