Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
845 views
in Technique[技术] by (71.8m points)

rust - Why it is not possible to use the ... syntax in expressions?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...