I recommend using strings as the base type for things like this, rather than ints. There is no need to use ints, just because that's what C uses.
Thomas On Fri, Sep 8, 2023 at 3:24 AM 'Mark' via golang-nuts < golang-nuts@googlegroups.com> wrote: > I often create small multi-value flag types, e.g. > ```go > type mode uint8 > > const ( > argMode mode = iota > baseMode > cmdMode > ) > ``` > The problem is that if I write, say, `m := baseMode`, although `m` has > the correct type (`mode`), there is no way to constrain its values to the > consts I've declared. > In theory I could create a `NewMode(int) mode` function and have it panic > if the given int isn't valid; but that won't prevent, say, `m += 99`. The > next step would be to define a full type, e.g., something like: > ```go > type mode struct { > m int > } > ``` > This would prevent `m++` and similar since all accesses would have to go > through the public functions. However, this would still do all its checking > at _runtime_; whereas for this kind of use it should surely be possible to > check at compile time. > > In Pascal it is easy to declare a "subrange" type which might look like > this in Go-like syntax: > > `type mode uint8 0..2` > > Is there a compile-time solution for this that I've missed? > > -- > You received this message because you are subscribed to the Google Groups > "golang-nuts" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to golang-nuts+unsubscr...@googlegroups.com. > To view this discussion on the web visit > https://groups.google.com/d/msgid/golang-nuts/8ba9ef87-984c-4b14-a760-343d2731e91dn%40googlegroups.com > <https://groups.google.com/d/msgid/golang-nuts/8ba9ef87-984c-4b14-a760-343d2731e91dn%40googlegroups.com?utm_medium=email&utm_source=footer> > . > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/CA%2BYjuxunOzRKt2vB9u8QtOmP%2Bwqavn7Yjky9jz4-C3b0%2BkAWRg%40mail.gmail.com.