I'm quite new to Go and would like to improve my code. I have a representation for access levels in Go like this:
type AccessLevelValue int
const (
GuestPermissions AccessLevelValue = 10
ReporterPermissions AccessLevelValue = 20
DeveloperPermissions AccessLevelValue = 30
MasterPermissions AccessLevelValue = 40
OwnerPermission AccessLevelValue = 50
)
What I want is a "constructor" for AccessLevelValue
to which I can pass a numeric value from {10,20,30,40,50}
and that returns me the according AccessLevelValue
. This is my current implementation, but it seems not so nice to me:
func int2AccessLevel(accessLevel int) *AccessLevelValue {
if accessLevel == 10 { return AccessLevel(GuestPermissions)}
if accessLevel == 20 { return AccessLevel(ReporterPermissions)}
if accessLevel == 30 { return AccessLevel(DeveloperPermissions)}
if accessLevel == 40 { return AccessLevel(MasterPermissions)}
if accessLevel == 50 { return AccessLevel(OwnerPermission)}
return nil
}
func AccessLevel(v AccessLevelValue) *AccessLevelValue {
p := new(AccessLevelValue)
*p = v
return p
}
Is there any cleaner implementation that doesn't need the if
statements and returns the same result?