如何在范围中包含最终值?

boh*_*nko 9 rust

我想创建一个带有'a'..'z'值(包括)的向量.

这不编译:

let vec: Vec<char> = ('a'..'z'+1).collect();
Run Code Online (Sandbox Code Playgroud)

什么是惯用的方式'a'..'z'

She*_*ter 13

Rust 1.26

从Rust 1.26开始,您可以使用"包含范围":

fn main() {
    for i in 0..=26 {
        println!("{}", i);
    }
}
Run Code Online (Sandbox Code Playgroud)

Rust 1.0到1.25

您需要在最终值中添加一个:

fn main() {
    for i in 0..(26 + 1) {
        println!("{}", i);
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您需要包含所有值,则无效:


但是,您无法迭代一系列字符:

error[E0277]: the trait bound `char: std::iter::Step` is not satisfied
 --> src/main.rs:2:14
  |
2 |     for i in 'a'..='z'  {
  |              ^^^^^^^^^ the trait `std::iter::Step` is not implemented for `char`
  |
  = note: required because of the requirements on the impl of `std::iter::Iterator` for `std::ops::RangeInclusive<char>`
Run Code Online (Sandbox Code Playgroud)

请参阅为什么不能收集一系列的char?解决方案.

我只想指定你感兴趣的字符集:

static ALPHABET: &str = "abcdefghijklmnopqrstuvwxyz";

for c in ALPHABET.chars() {
    println!("{}", c);
}
Run Code Online (Sandbox Code Playgroud)


小智 6

包含范围功能已稳定并作为版本1.26的一部分发布。以下是包含范围的有效语法

for i in 1..=3 {
    println!("i: {}", i);
}
Run Code Online (Sandbox Code Playgroud)