gpt4 book ai didi

rust - 如何在范围内包含最终值?

转载 作者:行者123 更新时间:2023-12-03 11:31:36 25 4
gpt4 key购买 nike

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

这不会编译:

let vec: Vec<char> = ('a'..'z'+1).collect();

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

最佳答案

rust 1.26

As of Rust 1.26,您可以使用“包含范围”:

fn main() {
for i in 0..=26 {
println!("{}", i);
}
}

Rust 1.0到1.25

您需要在最终值上加一个:
fn main() {
for i in 0..(26 + 1) {
println!("{}", i);
}
}

如果您需要包括所有值,则将无法使用:
  • How to iterate over all byte values (overflowing_literals in `0..256`)


  • 但是,您不能迭代一系列字符:

    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>`

    有关解决方案,请参见 Why can't a range of char be collected?

    我只需要指定您感兴趣的字符集即可:
    static ALPHABET: &str = "abcdefghijklmnopqrstuvwxyz";

    for c in ALPHABET.chars() {
    println!("{}", c);
    }

    关于rust - 如何在范围内包含最终值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61545884/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com