Why it is not possible to use the … syntax in expr

2020-04-14 12:54发布

I'm trying understand the ... syntax. Consider the following program:

fn how_many(x: i32) -> &'static str {
    match x {
        0 => "no oranges",
        1 => "an orange",
        2 | 3 => "two or three oranges",
        9...11 => "approximately 10 oranges",
        _ => "few oranges",
    }
}

fn pattern_matching() {
    for x in 0..13 {
        println!("{} : I have {} ", x, how_many(x));
    }
}

fn main() {
    // println!("{:?}", (2...6));
    pattern_matching();
}

In the above program, the 9...11 used in pattern matching compiles fine. When I try to use the same in like println!("{:?}", (2...6)); I get compilation error:

error: `...` syntax cannot be used in expressions
  --> src/main.rs:18:24
   |
18 |     println!("{:?}", (2...6));
   |                        ^^^
   |
   = help: Use `..` if you need an exclusive range (a < b)
   = help: or `..=` if you need an inclusive range (a <= b)

I'm trying to understand why it is not possible to use within println.

标签: rust
1条回答
2楼-- · 2020-04-14 13:21

For the same reason that you cannot use &*$# in expressions: it's not allowed by Rust's grammar. Rust decided to use different syntax for inclusive ranges. If you really care about the complete details, you can go read all 350+ comments on that issue.

The TL;DR:

  • No particular syntax was liked by everyone
  • ... is too close to a typo of ..
  • ... in patterns is already stabilized and must be supported forever, but it will be deprecated at some point and ..= will be preferred for that as well.

The error message tells you the appropriate syntax to use instead:

   = help: Use `..` if you need an exclusive range (a < b)
   = help: or `..=` if you need an inclusive range (a <= b)
fn how_many(x: i32) -> &'static str {
    match x {
        0 => "no oranges",
        1 => "an orange",
        2 | 3 => "two or three oranges",
        9..=11 => "approximately 10 oranges",
        _ => "few oranges",
    }
}

fn pattern_matching() {
    for x in 0..13 {
        println!("{} : I have {} ", x, how_many(x));
    }
}

fn main() {
    println!("{:?}", 2..=6);
    pattern_matching();
}
查看更多
登录 后发表回答