如何在一个范围内包含最终值? [英] How do I include the end value in a range?
本文介绍了如何在一个范围内包含最终值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建一个带有 'a'..'z' 值(含)的向量.
I wanted to create a vector with 'a'..'z' values (inclusive).
这不会编译:
let vec: Vec<char> = ('a'..'z'+1).collect();
'a'..'z'
的惯用方式是什么?
推荐答案
Rust 1.26
从 Rust 1.26 开始,您可以使用包含范围":
Rust 1.26
As of Rust 1.26, you can use "inclusive ranges":
fn main() {
for i in 0..=26 {
println!("{}", i);
}
}
Rust 1.0 到 1.25
您需要在最终值上加一个:
Rust 1.0 through 1.25
You need to add one to your end value:
fn main() {
for i in 0..(26 + 1) {
println!("{}", i);
}
}
如果您需要包含所有值,这将不起作用:
This will not work if you need to include all the values:
但是,您不能遍历一系列字符:
However, you cannot iterate over a range of characters:
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>`
有关解决方案,请参阅为什么不能收集一系列字符?.
See Why can't a range of char be collected? for solutions.
我只想指定您感兴趣的字符集:
I would just specify the set of characters you are interested in:
static ALPHABET: &str = "abcdefghijklmnopqrstuvwxyz";
for c in ALPHABET.chars() {
println!("{}", c);
}
这篇关于如何在一个范围内包含最终值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文