Lyn*_*ynn 20 syntax operators rust
我..=在一些Rust代码中看到了这个运算符:
for s in 2..=9 {
// some code here
}
Run Code Online (Sandbox Code Playgroud)
它是什么?
Lyn*_*ynn 25
这是包容性范围运算符.
该范围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]
Run Code Online (Sandbox Code Playgroud)
您还可以start..=end在match表达式中用作模式以匹配(包含)范围中的任何值.
match fahrenheit_temperature {
70..=89 => println!("What lovely weather!"),
_ => println!("Ugh, I'm staying in."),
}
Run Code Online (Sandbox Code Playgroud)
使用专用范围start..end作为模式是实验性功能.请参阅问题#37854.
包容性范围过去只是一个实验性的夜间特征,并且...之前已经编写过.
从Rust 1.26开始,它正式成为该语言的一部分,并编写..=.
(在包含范围存在之前,你实际上无法创建一系列字节值,包括255u8.因为它是0..256,并且256超出u8范围!这是问题#23635.)