在go中,我可以使用stringer将常量名称转换为字符串:
//go:generate stringer -type=M
type M int
const (
_ M = iota
Foo // "Foo"
Bar // "Bar"
)除了手写的开关之外,有没有什么方法可以让我将"foo"字符串转换为M类型的变量?
发布于 2020-09-16 23:16:41
我最近发现了https://github.com/alvaroloes/enumer,它添加了一个TypeString(string) Type方法,可以将字符串值转换为类型,并可以取代stringer。
发布于 2020-04-20 03:28:54
找到了一种方法,但它仍然是半手动的。通过使用stringer创建的映射切片,还可以对其进行搜索以反转操作:
type Measurement int
const (
invalidMeasurement Measurement = iota
Meters
Liters
Pounds
)
// Works with golang.org/x/tools/cmd/stringer
// v0.0.0-20200925191224-5d1fdd8fa346
func UnString(s string) Measurement {
s = strings.ToLower(s)
l := strings.ToLower(_Measurement_name)
for i := 0; i < len(_Measurement_index)-1; i++ {
if s == l[_Measurement_index[i]:_Measurement_index[i+1]] {
return Measurement(i)
}
}
//
return Measurement(0)
}https://stackoverflow.com/questions/61310161
复制相似问题