I've been using the "const iota" solution for enum like structures (see here). But recently I've hit a little SNAFU - one of my enums has reached it's limit of 64b (I'm using int64 consts). Any ideas, short of pouring myself into and over the hellish underbelly of math/big?
[Edit: Added example code]
package testy
import (
"fmt"
"strings"
"strconv"
)
type testyEnum int64
const (
TE1 testyEnum = 1 << iota
TE2
TE3
TE4
TE5
TE6
TE7
TE8
TE9
TE10
TE11
TE12
TE13
TE14
TE15
TE16
TE17
... (list shortened)
TE107
TE108
TE109
)
//HasFlag returns true if the caller has all of the flags from the parameter
func (obj testyEnum) HasFlag(right testyEnum) bool {
return obj & right == right
}
//ContainsSomeFlagOf returns true if the caller and the parameter share some flags.
func (obj testyEnum) ContainsSomeFlagOf(right testyEnum) bool {
return obj&right != 0
}
//SharedFlags returns the shared flags of enum and parameter
func (obj testyEnum) SharedFlags(right testyEnum) testyEnum {
return obj & right
}
//AddFlag(obj testyEnum) adds flag right to the enum
func (obj *testyEnum) AddFlag(right testyEnum) {
*obj = *obj|right
}
//RemoveFlag(obj testyEnum) removes flag right to the enum. If any of the flags from right where not set in obj.
func (obj *testyEnum) RemoveFlag(right testyEnum) {
shared := obj.SharedFlags(right)
*obj = *obj^shared
}
//ToInt(obj testyEnum) returns the value of the enum as int
func (obj *testyEnum) ToInt() int {
return int(*obj)
}
//ToStringSlice returns a slice of strings with all the flags that are set
func (obj *testyEnum) ToStringSlice() []string {
var flags []string
if obj.HasFlag(TE1) {
flags = append(flags, "TE1")
}
if obj.HasFlag(TE2) {
flags = append(flags, "TE2")
}
if obj.HasFlag(TE3) {
flags = append(flags, "TE3")
}
if obj.HasFlag(TE4) {
flags = append(flags, "TE4")
}
if obj.HasFlag(TE5) {
flags = append(flags, "TE5")
}
if obj.HasFlag(TE6) {
flags = append(flags, "TE6")
}
if obj.HasFlag(TE7) {
flags = append(flags, "TE7")
}
if obj.HasFlag(TE8) {
flags = append(flags, "TE8")
}
if obj.HasFlag(TE9) {
flags = append(flags, "TE9")
}
if obj.HasFlag(TE10) {
flags = append(flags, "TE10")
}
if obj.HasFlag(TE11) {
flags = append(flags, "TE11")
}
if obj.HasFlag(TE12) {
flags = append(flags, "TE12")
}
if obj.HasFlag(TE13) {
flags = append(flags, "TE13")
}
if obj.HasFlag(TE14) {
flags = append(flags, "TE14")
}
if obj.HasFlag(TE15) {
flags = append(flags, "TE15")
}
if obj.HasFlag(TE16) {
flags = append(flags, "TE16")
}
... (ditto)
if obj.HasFlag(TE107) {
flags = append(flags, "TE107")
}
if obj.HasFlag(TE108) {
flags = append(flags, "TE108")
}
if obj.HasFlag(TE109) {
flags = append(flags, "TE109")
}
return flags
}
//String returns a string representation of the enum
func (obj testyEnum) String() string {
flags := obj.ToStringSlice()
if len(flags) > 0 {
return fmt.Sprintf("testyEnum{%d(%s)}", int(obj), strings.Join(flags, "|"))
}
return "testyEnum{0()}"
}