How do you loop through the fields in a Golang struct to get and set values in an extensible way?

前端 未结 5 1602
孤城傲影
孤城傲影 2021-02-07 06:42

I have a struct Person.

type Person struct {
    Firstname string       
    Lastname  string       
    Years     uint8       
}

Then I have t

5条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-07 07:22

    I don't even know how many ways this can go wrong...

    package main
    
    import (
        "fmt"
        "encoding/json"
    )
    
    type Serializable interface {
        fromMap(map[string]interface{}) error
        toMap() (map[string]interface{}, error)
    }
    
    type Person struct {
        Firstname string       
        Lastname  string       
        Years     uint8       
    }
    
    func (p *Person) fromMap(m map[string]interface{}) error {
        b, err := json.Marshal(m)
        if err != nil {
            return err
        }
    
        if err := json.Unmarshal(b, p); err != nil {
            return err
        }
        return nil
    }
    
    func (p Person) toMap() (map[string]interface{}, error) {
        b, err := json.Marshal(p)
        if err != nil {
            return nil, err
        }
        m := map[string]interface{}{}
        if err := json.Unmarshal(b, &m); err != nil {
            return nil, err
        }
        return m, nil
    }
    
    func copy(p1 Serializable, p2 Serializable) error {
    
        m1, err := p1.toMap()
        if err != nil {
            return err
        }
    
        m2, err := p2.toMap()
        if err != nil {
            return err
        }
    
        for k := range m1 {
            m2[k] = m1[k]
        }
    
        if err := p2.fromMap(m2); err != nil {
            return err
        }
        return nil
    }
    
    func main() {
        p1 := Person{
            "Mary",
            "Jane",
            26,
        }
    
        p2 := Person {
            "Random",
            "Lady",
            26,
        }
    
        if err := copy(&p1, &p2); err != nil {
            fmt.Printf("ERR: %s\n", err.Error())
            return
        }
    
        fmt.Printf("%v\n", p2)
    
    }
    

提交回复
热议问题