Enums: using const instead of var?
frederikhors opened this issue · comments
frederikhors commented
I continue to write here coming from the post's comment.
I think it's a great idea to use functions because I can reduce the code noticeably having even more security (because I don't use simple strings anymore).
type StateEnum struct {
slug string
}
-func (o StateEnum) Is(s string) bool {
- return o.slug == s
+func (o StateEnum) Is(s StateEnum) bool {
+ return o == s
}
func (o StateEnum) String() string {
return o.slug
}
-const (
- Draft = "DRAFT"
- Completed = "COMPLETED"
- Approved = "APPROVED"
- Rejected = "REJECTED"
-)
-
-func NewStateEnumFromString(s string) StateEnum {
- switch s {
- case Draft:
- return StateEnum{Draft}
- case Completed:
- return StateEnum{Completed}
- case Approved:
- return StateEnum{Approved}
- case Rejected:
- return StateEnum{Rejected}
- default:
- panic("unknown StateEnum")
- }
-}
+func Draft() StateEnum { return StateEnum{"DRAFT"} }
+func Completed() StateEnum { return StateEnum{"COMPLETED"} }
+func Approved() StateEnum { return StateEnum{"APPROVED"} }
+func Rejected() StateEnum { return StateEnum{"REJECTED"} }
But, there is a but.
In some parts of my codebase I need to marshal and unmarshal from string.
So I need again the func NewStateEnumFromString()
, right?
Miłosz Smółka commented
Hey @frederikhors!
Yes, you still need the function. But it should be fine to keep all of the functions you have there. You can use NewStateEnumFromString
for unmarshaling, and the other functions like regular enums in the code. :)