I have a list of access rights:
const (
Everyone = 0
Owner = 1
Administrator = 2
)
And a struct representing Routes:
type Route struct {
Name string
Method string
Pattern string
HandlerFunc http.HandlerFunc
AccessLevel uint64
}
How can I restrict AccessLevel
field value of the Route
struct be only one of those const from above?
You can't. Go doesn't support enums. However, you can get close to it. Just introduce a separate type for your access level:
type AccessLevel uint64
and make the consts be of the type:
const (
Everyone AccessLevel = 0
Owner = 1
Administrator = 2
)
Then define the Field to be of that type:
type Route struct {
// ...
AccessLevel AccessLevel
}
Now you can assign those consts, but not a "normal" uint64
.
The caveat is that you can still type convert a uint64
to a AccessLevel
via AccessLevel(1234)
.
The only way to impose this type of restriction is by not exporting the field, and doing your checks in any setter method(s).
type Route struct {
Name string
Method string
Pattern string
HandlerFunc http.HandlerFunc
accessLevel uint64
}
// AccessLevel getter method
func (r Route) AccessLevel() uint64 {
return r.accessLevel
}
// SetAccessLevel setter method
func (r Route) SetAccessLevel(value uint64) error {
if value < 0 || value > 2 {
return errors.New("AccessLevel must be between 0 and 2, inclusive")
}
r.accessLevel = value
return nil
}