如何生成一个包含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:rangerange_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.

Rust相关问答推荐

常量泛型和类型枚举箱有重叠的用途吗?

在Rust中赋值变量有运行时开销吗?

有没有办法在Rust中配置常量变量的值?

在生存期内将非静态可变引用转换为范围内的静态可变引用

AXUM一路由多个不包括URL的参数类型

如何防止Cargo 单据和Cargo 出口发布( crate )项目

Windows 上 ndarray-linalg 与 mkl-stats 的链接时间错误

为什么在 Allocator API 中 allocate() 使用 `[u8]` 而 deallocate 使用 `u8` ?

如何强制匹配的返回类型为()?

可以在旋转循环中调用try_recv()吗?

注释闭包参数强调使用高阶排定特征界限

Rust 中的生命周期:borrow 的 mut 数据

为什么 `tokio::join!` 宏不需要 Rust 中的 `await` 关键字?

我的 Axum 处理程序无法编译:未实现 IntoResponse 特征

从现有系列和 map 值创建新系列

使用 HashMap 条目时如何避免字符串键的短暂克隆?

从函数返回 u32 的数组/切片

TcpStream::connect - 匹配武器具有不兼容的类型

制作嵌套迭代器的迭代器

提取 struct 生成宏中字段出现的索引