我正在尝试从枚举的reflect.Type和值 https://play.golang.org/p/PqklMe_Z4WX 创建一个enum实例
package main import ( "fmt" "reflect" type WeekDay string const ( SUNDAY WeekDay = "sunday" MONDAY WeekDay = "monday" func (day WeekDay) WeekDay() bool { switch day { case SUNDAY, MONDAY: return true default: return false func main() { rt := reflect.TypeOf(WeekDay("sunday")) x := reflect.New(rt) x = x.Elem() x.Set(reflect.ValueOf("sunday")) fmt.Println(x.Interface()) }
有没有办法在golang中创建一个enum的实例,它的类型和可能的常量值?
发布于 2018-06-05 07:50:38
使用 reflect.New(t).Elem() 获取值,使用 SetString 设置值。
reflect.New(t).Elem()
SetString
// t is the reflect.Type for a Weekday t := reflect.TypeOf(WeekDay("sunday"))