by fullstackchris · 1y ago · 0 comments
import "fmt"
// Define an enumeration for status type Status int
const ( Pending Status = iota InProgress Completed Failed )
func (s Status) String() string { return [...]string{"Pending", "InProgress", "Completed", "Failed"}[s] }
func main() { var s Status = InProgress fmt.Println(s) // Output: InProgress }
In your suggested method it doesn’t even catch that case and provide an error if the value isn’t in the range.
I think parent should be using `stringer` [2] instead.
I didn't say anything along those lines, in fact I was commenting generally about this issue that you guys and the other commenters mentioned.
I was just suggesting a solution to the the problem stated.
const ( Pending Status = iota InProgress Completed Cancelled Failed )
func (s Status) String() string { return [...]string{"Pending", "InProgress", "Completed", "Failed"}[s] }
func main() { var s Status = Cancelled fmt.Println(s) // Output: ??
If the compiler - not some linter - protests that the list of names is different from the number of items in the enum, then I think this is at least a half-decent design of an enum type. Not a great one (because the author still had to repeat the names), but at least something that isn't a fundamentally broken design of an enum type.
But if the compiler is silent, and the output of the Println(Cancelled) is "Failed" then I'm not angry, I'm disappointed.
Only one step better than Assembly or Fortran.