Skip Navigation
InitialsDiceBearhttps://github.com/dicebear/dicebearhttps://creativecommons.org/publicdomain/zero/1.0/„Initials” (https://github.com/dicebear/dicebear) by „DiceBear”, licensed under „CC0 1.0” (https://creativecommons.org/publicdomain/zero/1.0/)MO
MotokEkb @lemmy.world

Dev, FOSS enthusiast, gamer

Posts 1
Comments 2

How can I limit a number to a certain range in a struct/enum definition?

Say I want to have a struct called Tile that will have a suit (let it be a string for simplicity's sake) and a number. This number can only exist in the range of 1-9.

In Nim, for example, you can do something like this:

``` type Tile = object suit: string num: range[1..10]

var t = Tile(suit: "test", num: 9) echo t.num # 9 t.num += 2 # OverflowDefect ```

How can I do such a thing in Rust? I can only think of one way: not allowing the number to be out of range in the "new" constructor and then adding auxiliary methods (add, sub, etc.) that do bounds checking. This solution seems too complex, though. There might be a way to do this using various range traits, but I can't seem to figure out how.

4
What are y'all's all time favourite game OSTs?
  • For me it's either TF2 or Hearts of Iron IV. HOI soundtrack is very epic and grand and you never know what you'll get with TF2. It can either be the most goofy music you've ever heard, or it's the kind of music that will make you cry at 3 am.