【问题标题】:goyaml convert string to int constantgoyaml 将字符串转换为 int 常量
【发布时间】:2016-11-18 20:41:40
【问题描述】:

假设我们有以下 go 代码

type SectionType int

const (
    Header SectionType = iota
    Footer
    Body
)

var sectionTypeNames = map[string]SectionType{
  "header": Header
  "footer": Footer
  "body":   Body
}

type Page struct {
    Sections: []SectionType `yaml:"sections"`
}

我们有以下yaml

page1:
  - header
  - body

有没有办法让 goyaml 将“header”和“body”的字符串转换为它们各自的 int 常量类型(定义在 sectionTypeNames 映射中)我们反序列化 Page 结构?

【问题讨论】:

    标签: go yaml


    【解决方案1】:

    go-yaml 无法自动执行此操作,因为它只能看到 package reflect 公开的有关类型的内容,并且不包括包中的常量名称。从reflect 的角度来看,根本没有包的概念。

    听起来你愿意自己做(你已经做了一个map,等等)。所以我认为可以做的就是将SectionType*[]SectionType变成Unmarshaler,通过提供一个函数将YAML包解码的字符串转换为值;我缺乏go-yaml 的具体经验,无法准确告诉您如何实现它,但总的来说,这就是Unmarshaler 之类的接口所做的。

    如果您经常遇到这种情况,那么可能值得按照stringer 的方式编写一些东西来为您生成映射和反序列化函数(通过检查定义类型的源文件)。不过,必须有很多类型才值得。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-24
      • 2011-10-02
      • 2011-03-06
      • 1970-01-01
      • 2018-07-05
      相关资源
      最近更新 更多