Rust中的.. =(点点等于)运算符是什么?

问题描述 投票:20回答:1

我在一些Rust代码中看到了这个..=运算符:

for s in 2..=9 {
    // some code here
}

它是什么?

syntax rust operators
1个回答
25
投票

这是inclusive range operator

范围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..256256超出了u8范围!这是issue #23635。)

也可以看看

© www.soinside.com 2019 - 2024. All rights reserved.