卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章35122本站已运行394

如何重用第三方包中的结构,同时更改单个字段的编组行为?

如何重用第三方包中的结构,同时更改单个字段的编组行为?

php小编子墨在这里分享一个关于如何重用第三方包中的结构并更改单个字段编组行为的技巧。当我们使用第三方包时,有时候我们需要对其中的某个字段进行自定义编组。本文将介绍一个简单的方法,可以通过继承和重写的方式来实现这一目标,既能重用原有的结构,又能满足个性化需求。接下来让我们一起来看看具体的实现方法吧!

问题内容

假设我想将一个结构编组到 YAML 中,并且该结构已经定义了其所有 YAML 标记,但有一个我想要更改的标记除外。如何在不更改结构本身的情况下更改此单个字段的行为?假设该结构来自第三方包。

这是一个要演示的示例,以及我的最佳尝试。假设 User 结构(及其关联的 Secret 结构)来自第三方包,因此我们无法修改它们。

package main

import (
    "fmt"

    "gopkg.in/yaml.v2"
)

type User struct {
    Email    string  `yaml:"email"`
    Password *Secret `yaml:"password"`
}

type Secret struct {
    s string
}

// MarshalYAML implements the yaml.Marshaler interface for Secret.
func (sec *Secret) MarshalYAML() (interface{}, error) {
    if sec != nil {
        // Replace `"<secret>"` with `sec.s`, and it gets the desired
        // behavior. But I can't change the Secret struct:
        return "<secret>", nil
    }
    return nil, nil
}

func (sec *Secret) UnmarshalYAML(unmarshal func(interface{}) error) error {
    var st string
    if err := unmarshal(&st); err != nil {
        return err
    }
    sec.s = st
    return nil
}

// My best attempt at the solution:
type SolutionAttempt struct {
    User
}

func (sol *SolutionAttempt) MarshalYAML() (interface{}, error) {
    res, err := yaml.Marshal(
        struct {
            // I don't like having to repeat all these fields from User:
            Email    string `yaml:"email"`
            Password string `yaml:"password"`
        }{
            Email:    sol.User.Email,
            Password: sol.User.Password.s,
        },
    )
    if err != nil {
        return nil, err
    }
    return string(res), nil
}

func main() {
    user := &User{}
    var data = `
  email: [email protected]
  password: asdf
`
    err := yaml.Unmarshal([]byte(data), user)
    if err != nil {
        fmt.Printf("errors! %s", err)
        return
    }

    buf, err := yaml.Marshal(user)
    if err != nil {
        fmt.Printf("errors! %s", err)
        return
    }

    // Without touching User or Secret, how can I unmarshall an
    // instance of User that renders the secret?
    fmt.Printf("marshalled output:n%sn", buf)

    ///////////////////////////////////////////////////////
    // attempted solution:
    ///////////////////////////////////////////////////////
    sol := &SolutionAttempt{}
    var data2 = `
user:
    email: [email protected]
    password: asdf
`
    err = yaml.Unmarshal([]byte(data2), sol)
    if err != nil {
        fmt.Printf("errors! %s", err)
        return
    }

    buf, err = yaml.Marshal(sol)
    if err != nil {
        fmt.Printf("errors! %s", err)
        return
    }
    fmt.Printf("attempted solution marshalled output:n%sn", buf)
}

这是上述代码的 Go Playground 链接:https://go.dev/play/p/ojiPv4ylCEq

解决方法

这根本不可能。

你的“最佳尝试”就是正确的道路。

卓越飞翔博客
上一篇: 如何使用 go-github 对 Github 问题发表评论?
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏