What is the ..= (dot dot equals) operator in Rust?

点点圈 提交于 2019-12-08 14:34:10

问题


I saw this ..= operator in some Rust code:

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

What is it?


回答1:


This is the inclusive range operator.

The range x..=y contains all values >= x and <= y, i.e. “from x up to and including y”.

This is in contrast to the non-inclusive range operator x..y, which doesn't include y itself.

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]

Match expressions

You can also use start..=end as a pattern in a match expression to match any value in the (inclusive) range.

match fahrenheit_temperature {
    70..=89  => println!("What lovely weather!"),
    _        => println!("Ugh, I'm staying in."),
}

(Using an exclusive range start..end as a pattern is an experimental feature.)

History

Inclusive ranges used to be an experimental nightly-only feature, and were written ... before.

As of Rust 1.26, it's officially part of the language, and written ..=.

(Before inclusive ranges existed, you actually couldn't create, say, a range of byte values including 255u8. Because that'd be 0..256, and 256 is out of the u8 range! This is issue #23635.)

See also

  • The Rust 1.26 release blog post's introduction to ..=.
  • StackOverflow: How do I include the end value in a range?


来源:https://stackoverflow.com/questions/52932572/what-is-the-dot-dot-equals-operator-in-rust

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!