goyaml将字符串转换为整数常量

huangapple go评论95阅读模式
英文:

goyaml convert string to int constant

问题

假设我们有以下的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

在反序列化Page结构时,有没有办法让goyaml将字符串"header"和"body"转换为它们对应的整数常量类型(如sectionTypeNames映射中定义的)?

英文:

Suppose we have the following go code

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"`
}

And we have the following yaml

page1:
  - header
  - body

Is there a way to get goyaml to convert the strings of "header" and "body" into their respective int constant types (as defined in sectionTypeNames map) we deserializing the Page struct?

答案1

得分: 2

go-yaml无法自动完成此操作,因为它只能看到package reflect公开的类型信息,其中不包括包中常量的名称。从reflect的角度来看,实际上并没有包的概念。

根据你的描述,你似乎愿意自己完成这个操作(你已经创建了一个map等)。所以,我认为你可以将SectionType*[]SectionType作为Unmarshaler,通过提供一个将YAML包解码的字符串转换为值的函数来实现;我对go-yaml的具体经验不足以告诉你如何准确实现它,但一般来说,这就是Unmarshaler等接口的作用。

如果你经常遇到这种情况,编写类似stringer的工具可能是值得的,它可以为你生成映射和反序列化函数(通过检查定义类型的源文件)。不过,在这种情况下,必须有很多类型才值得这样做。

英文:

go-yaml can't do it automatically because it can only see what package reflect exposes about types, and that doesn't include the names of constants in a package. There isn't really a notion of packages from reflect's perspective at all.

It sounds like you're willing to do it yourself (you've already made a map, etc). So I think what you can do is make SectionType or *[]SectionType an Unmarshaler, by providing a function that turns the strings the YAML package decodes into values; I lack the specific experience with go-yaml to be able to tell you exactly how to implement it, but in general that's what interfaces like Unmarshaler do.

If this is something you run into often enough, it might be worthwhile writing something along the lines of stringer to generate the maps and deserialization functions for you (by inspecting the source files that define the types). There have to be a lot of types before that's worthwhile though.

huangapple
  • 本文由 发表于 2016年11月19日 04:41:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/40685601.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定