4
submitted 1 year ago by MotokEkb@lemmy.world to c/rust@lemmy.ml

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.

you are viewing a single comment's thread
view the rest of the comments
[-] refefer@programming.dev 4 points 1 year ago* (last edited 1 year ago)

You reminded me of a deeply amusing story of solving the 4 queens problem with just the type system.

this post was submitted on 19 Jun 2023
4 points (100.0% liked)

Rust Programming

7734 readers
1 users here now

founded 5 years ago
MODERATORS