我想动态更改一个结构体的注释并像下面这样使用
yaml.Unmarshal
:package main
import (
"fmt"
"reflect"
"gopkg.in/yaml.v3"
)
type User struct {
Name string `yaml:"dummy"`
}
func (u *User) UnmarshalYAML(node *yaml.Node) error {
value := reflect.ValueOf(*u)
t := value.Type()
fields := make([]reflect.StructField, 0)
for i := 0; i < t.NumField(); i++ {
fields = append(fields, t.Field(i))
if t.Field(i).Name == "Name" {
fields[i].Tag = `yaml:"name"` // Dynamic annotation
}
}
newType := reflect.StructOf(fields)
newValue := value.Convert(newType)
err := node.Decode(newValue.Interface()) // Cause error because it's not pointer
return err
}
var dat string = `name: abc`
func main() {
out := User{}
yaml.Unmarshal([]byte(dat), &out)
fmt.Printf("%+v\n", out)
}
它会导致错误,例如panic: reflect: reflect.Value.Set using unaddressable value [recovered]
,我认为这是因为node.Decode
没有使用指针。那么如何创建新类型的指针?