纵梁工具是否有“反向”功能?

在 go 中,我可以使用stringer将 const 名称转换为字符串:


//go:generate stringer -type=M

type M int


const (

    _ M = iota

    Foo // "Foo"

    Bar // "Bar"

)

除了手写开关之外,还有什么可以让我将"foo"字符串转换为类型变量的吗?M


GCT1015
浏览 107回答 2
2回答

开心每一天1111

找到了一种方法,但它仍然是半手动的。通过使用 stringer 创建的映射切片,也可以搜索它以反转操作:type Measurement intconst (&nbsp; &nbsp; invalidMeasurement Measurement = iota&nbsp; &nbsp; Meters&nbsp; &nbsp; Liters&nbsp; &nbsp; Pounds)// Works with golang.org/x/tools/cmd/stringer// v0.0.0-20200925191224-5d1fdd8fa346func UnString(s string) Measurement {&nbsp; &nbsp; s = strings.ToLower(s)&nbsp; &nbsp; l := strings.ToLower(_Measurement_name)&nbsp; &nbsp; for i := 0; i < len(_Measurement_index)-1; i++ {&nbsp; &nbsp; &nbsp; &nbsp; if s == l[_Measurement_index[i]:_Measurement_index[i+1]] {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return Measurement(i)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; //&nbsp;&nbsp; &nbsp; return Measurement(0)}

斯蒂芬大帝

我最近发现了https://github.com/alvaroloes/enumer,它添加了一个TypeString(string) Type方法,可以将字符串值转换为类型并且可以替换stringer.
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go