我在一些Rust代码中看到了这个..=
运算符:
for s in 2..=9 {
// some code here
}
它是什么?
范围x..=y
包含所有值>= x
和<= y
,即“从x
到包括y
”。
这与非包容性范围运算符x..y
形成对比,后者不包括y
本身。
fn main() {
println!("{:?}", (10..20) .collect::<Vec<_>>());
println!("{:?}", (10..=20).collect::<Vec<_>>());
}
// Output:
//
// [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
// [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
您还可以使用start..=end
作为match
表达式中的模式来匹配(包含)范围中的任何值。
match fahrenheit_temperature {
70..=89 => println!("What lovely weather!"),
_ => println!("Ugh, I'm staying in."),
}
(使用独家范围start..end
作为模式是experimental feature。)
包容性范围以前只是一个实验性的夜间特征,之前写过...
。
从Rust 1.26开始,它正式成为该语言的一部分,并编写了..=
。
(在包含范围存在之前,你实际上无法创建一系列字节值,包括255u8
。因为那是0..256
,256
超出了u8
范围!这是issue #23635。)