In GO I want to create enum like in C++ style: ClassName::EnumName::EnumValue.
struct MyClass { enum class EnumName { Success, Error }; }; GO variant:
package MyPackage type enumValue struct { val int } type knownValus struct { Success, Error enumValue } var EnumName = knownValus { Success: enumValue{0}, Error: enumValue{1}, } I have a lot of enums in my C++ class it is very important for me to keep this enum name. When I type enum name I want to see all the possible known values for this specific enum to be able to choose the proper one. One more advantage: we can pass this enum to a function:
func HandleSmth(v enumValue) {} MyPackage.HandleSmth(MyPackage.EnumName.Success) This is incredible! I will not be able to call my function with a different data type!
And what about Enum in style like this:
const ( Success = iota Error = iota ) It's pretty ugly because I cannot figure out the proper values that my function can handle.
The question is: how to implement general EnumToString function that will allow me to convert any enum from a private packages to a string?
I've implemented this for a specific type struct, but I cannot for a general...
package EnumToString func Convert(result enumValue) string { possibleEnums := EnumName elems := reflect.ValueOf(&possibleEnums).Elem() if elems.NumField() == 0 { panic("No fields found") } GetUnexportedField := func(field reflect.Value) interface{} { return reflect.NewAt(field.Type(), unsafe.Pointer(field.UnsafeAddr())).Elem().Interface() } typeOfT := elems.Type() for i := 0; i < elems.NumField(); i++ { field := elems.Field(i) valStruct := GetUnexportedField(field).(enumValue) val := GetUnexportedField(reflect.ValueOf(&valStruct).Elem().Field(0)) switch val.(type) { case int: if val.(int) == GetUnexportedField(reflect.ValueOf(&result).Elem().Field(0)).(int) { return typeOfT.Field(i).Name } } } return "" } fmt.printLn(EnumToString.Convert(MyPackage.EnumName.Success)) // Should print 'Success' fmt.printLn(EnumToString.Convert(OtherPackage.OtherName.OtherVale)) // Should print 'OtherValue' But my approach works for the only one specific struct.
How to make it working with any structs?