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

前端 未结 5 1601
孤城傲影
孤城傲影 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:25

    You should use a map[string]interface{} instead, gonna be much faster (although still not as fast as you used the proper logic with actual structs).

    package main
    
    import "fmt"
    
    type Object map[string]interface{}
    
    var m = Object{
        "Firstname": "name",
        "Lastname":  "",
        "years":     uint8(10),
    }
    
    func main() {
        var cp = Object{}
        for k, v := range m {
            if s, ok := v.(string); ok && s != "" {
                cp[k] = s
            } else if ui, ok := v.(uint8); ok {
                cp[k] = ui
            }
        }
        fmt.Printf("%#v\n", cp)
    }
    

提交回复
热议问题