Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enums: using const instead of var? #4

Open
frederikhors opened this issue Jan 17, 2022 · 1 comment
Open

Enums: using const instead of var? #4

frederikhors opened this issue Jan 17, 2022 · 1 comment

Comments

@frederikhors
Copy link

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?

@m110
Copy link
Member

m110 commented Jan 19, 2022

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. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants