您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

自定义UnmarshalYAML,如何在自定义类型上实现Unmarshaler接口

自定义UnmarshalYAML,如何在自定义类型上实现Unmarshaler接口

由于@Volker并未发布他的评论作为答案,因此我会为了完整性而这样做。 所以我已经走在正确的道路上,但是在初始化它时却无法取消引用我的结构的指针接收器:

// Implements the Unmarshaler interface of the yaml pkg.
func (e *EpnSeq) UnmarshalYAML(unmarshal func(interface{}) error) error {
    yamlEpnSequence := make([]uint16, 0)
    err := unmarshal(&yamlEpnSequence)
    if err != nil {
        return err
    }

    // make sure to dereference before assignment, 
    // otherwise only the local variable will be overwritten
    // and not the value the pointer actually points to
    *e = make(EpnSeq, len(yamlEpnSequence))
    for priority, epn := range yamlEpnSequence {
        e[epn] = uint16(priority) // no crash anymore
    }

    return nil
}
其他 2022/1/1 18:16:01 有435人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶