实现说明
区间边界:半开与包含以函数 main为骨架。
for i in 0..letters.len() 是唯一的迭代点——其余代码顺序执行一遍。
使用要点
- 跑完文件,输出里会留下标记——
inclusive:、contains 30:、contains 70:。
常见问题
运行「区间边界:半开与包含」会打印什么?
文件本身就是完整程序,直接运行——输出行带有 inclusive:、contains 30:、contains 70: 这类标签。
核心语句
let countdown: Vec<i32> = (1..=3).rev().collect();
代码示例
fn main() {
// half-open: excludes the end, so it composes with len()
let letters = ['a', 'b', 'c', 'd', 'e'];
for i in 0..letters.len() {
print!("{} ", letters[i]);
}
println!();
// ..= is the inclusive form, so 'a'..='e' covers five chars
let mut inclusive = String::new();
for ch in 'a'..='e' {
inclusive.push(ch);
}
println!("inclusive: {inclusive}");
// ranges are values: contains and is_empty test bounds without looping
let working = 18..=65;
println!("contains 30: {}", working.contains(&30));
println!("contains 70: {}", working.contains(&70));
// rev walks the same bounds backwards; start > end is empty, not an error
let countdown: Vec<i32> = (1..=3).rev().collect();
println!("rev: {countdown:?}");
println!("5..1 is_empty: {}", (5..1).is_empty());
}