英文:
golang yaml marshal url
问题
我正在尝试处理具有URL字段的配置文件,并且我想要编组和解组这种类型。文档指出我可以使用自定义编组函数。
在这个 Golang Playground 中,你可以看到自定义的解组函数工作正常,但自定义的编组函数却不起作用:
type YAMLURL struct {
*url.URL
}
func (j *YAMLURL) UnmarshalYAML(unmarshal func(interface{}) error) error {
fmt.Println("自定义解组函数")
var s string
err := unmarshal(&s)
if err != nil {
return err
}
url, err := url.Parse(s)
j.URL = url
return err
}
func (j *YAMLURL) MarshalYAML() (interface{}, error) {
fmt.Println("自定义编组函数")
return j.String(), nil
}
https://go.dev/play/p/24JbJEhi1Q8
我不知道为什么会出现这种情况。谢谢。
英文:
I'm trying to work with configuration files which have url fields and I would like to marshal and unmarshal this type.
The documentation point that I can do a custom marshal function.
In this golang playground you can see that the custom unmarshal function works fine but not the custom marshal function:
type YAMLURL struct {
*url.URL
}
func (j *YAMLURL) UnmarshalYAML(unmarshal func(interface{}) error) error {
fmt.Println("custom unmarshal function")
var s string
err := unmarshal(&s)
if err != nil {
return err
}
url, err := url.Parse(s)
j.URL = url
return err
}
func (j *YAMLURL) MarshalYAML() (interface{}, error) {
fmt.Println("custome marshal")
return j.String(), nil
}
https://go.dev/play/p/24JbJEhi1Q8
I don't know why
Thanks
答案1
得分: 1
问题在于你为指针接收器编写了MarshalYAML
方法,因此你可以在指针类型上调用此方法,同时你在Configuration
结构体的URI
属性上定义了一个非指针(根据你粘贴的playground链接)。
所以你要么将URI
属性类型更改为*YAMLURL
(而不是YAMLURL
):
type A struct {
URI *YAMLURL `yaml:"url"`
}
要么将MarshalYAML
定义为非指针接收器(也称为值接收器),像这样:
func (j YAMLURL) MarshalYAML() (interface{}, error) {
fmt.Println("custom marshal")
return j.String(), nil
}
英文:
The problem is that you wrote the MarshalYAML
method for a pointer receiver, so you can call this method on a pointer type, meanwhile you defined the URI
attribute of your A
on Configuration
struct, as a non pointer ( based on the playground link you pasted ).
So you have to either change the URI
attribute type to *YAMLURL
( instead of YAMLURL
):
type A struct {
URI *YAMLURL `yaml:"url"`
}
or define the MarshalYAML
as a non-pointer receiver ( aka. Value receiver ), like this:
func (j YAMLURL) MarshalYAML() (interface{}, error) {
fmt.Println("custome marshal")
return j.String(), nil
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论