How to constrain an integral type's values

104 views
Skip to first unread message

Mark

unread,
Sep 8, 2023, 3:24:09 AM9/8/23
to golang-nuts
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?

Jan Mercl

unread,
Sep 8, 2023, 3:33:01 AM9/8/23
to Mark, golang-nuts
On Fri, Sep 8, 2023 at 9:24 AM 'Mark' via golang-nuts
<golan...@googlegroups.com> wrote:

> Is there a compile-time solution for this that I've missed?

No. Go does not have enum types.

Thomas Bushnell BSG

unread,
Sep 8, 2023, 10:17:29 AM9/8/23
to Mark, golang-nuts
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

--
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...@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.
Reply all
Reply to author
Forward
0 new messages