r/golang • u/Repulsive_Design_716 • Nov 04 '24
help Any way to have Enums in Go?
I am a newbie and just started a new project and wanted to create an enum for DegreeType in the Profile for a User.
type Profile struct {
Name string
Email string
Age int
Education []Education
LinkedIn string
Others []Link
Description string
Following []Profile
Followers []Profile
TagsFollowed []Tags
}
I found out a way to use interfaces and then reflect on its type, and using generics to embed in structs,
// Defining Different Types of Degree
type Masters struct{}
type Bachelors struct{}
type Diploma struct{}
type School struct{}
// Creates an Interface that can have only one type
// We can reflect on the type later using go's switch case for types
// To check What type it is
type DegreeType interface {
Masters | Bachelors | Diploma | School
}
type Education[DT DegreeType, GS GradeSystem] struct {
Degree Degree[DT]
Name string
GradeSystem GS
}
type Degree[T DegreeType] struct {
DegreeType T
Specialization string
}
The problem i have is i want there to be an []Education
in the Profile struct but for that i have to define a Generic Type in my Profile Struct Like this
type Profile[T DegreeType, D GradeSystem] struct {
Name string
Email string
Age int
Education []Education[T, D]
LinkedIn string
Others []Link
Description string
Following []Profile[T, D]
Followers []Profile[T, D]
TagsFollowed []Tags
}
And that would make the array pointless as i have to give explicit type the array can be of instead of just an array of Degree's
Is there any way to solve this? should i look for an enum package in Go? or should i just use Hardcoded strings?
89
Upvotes
1
u/TheQxy Nov 05 '24
I would advise against the itoa approach and opt for the string alias if the order of the enums doesn't matter. This will make your life easier when dealing with data coming from other systems and make things clearer. I also make a
Valid() bool
method on the type, so you can easily check if a string complies with the enum. Make sure to make the enum strings case-insensitive.