英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论