Better way to use constants in match statements?

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=0f6fdce5c8620ee74323c462df94e28e

I was hoping to use const GIGABYTE: u64 = 1073741824; to make matching on a file size a little more readable.

I was surprised to see that I can match with a constant, but I can't match on e.g. GIGABYTE+1 or 2*GIGABYTE, which gives syntax errors (with or without parentheses -- thought it may be an order of operations issue).

I was even more surprised to see that I can't work around by calculating a value and using that for the range (let two_gigs = 2*GIGABYTE).

Is the best way to go about this just defining additional consts?

Is there a better strategy for naming interesting constants that you want to use in match patterns?

const GIG_PLUS_ONE: u64 = 1+GIGABYTE;
const TWO_GIGS: u64 = 2*GIGABYTE;
...
match md.len() {
    0..=GIGABYTE => ...
    GIG_PLUS_ONE..=TWO_GIGS => ...
    _ => ...
}
1 Like

On nightly there' inline_const - The Rust Unstable Book, but nothing for that in stable yet.

1 Like

Oh that will be nice!

It's worth mentioning, you don't have to define const items at an outer scope, for instance, if you replace

let two_gigs = 2*GIGABYTE

with

const two_gigs: u64 = 2*GIGABYTE

it will work. It's a little more verbose, but it might suit you here.

1 Like

This is what I ended up doing, with another one for gig_plus_one, since half-open ranges are also not stable yet.

You could also just have the second one be 0..=TWO_GIGS, since they run in order, if you prefer. (But I generally support the "make them distinct" instinct.)

That hadn't occurred to me for some reason but makes perfect sense, and would probably be fine in this instance.

1 Like