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

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

    Here is the solution f2.Set(reflect.Value(f)) is the key here

    package main
    
       import (
        "fmt"
        "reflect"
       )
    
       func main() {
        type T struct {
            A int
            B string
        }
        t := T{23, "skidoo"}
        t2:= T{}
        s := reflect.ValueOf(&t).Elem()
        s2 := reflect.ValueOf(&t2).Elem()
        typeOfT := s.Type()
        fmt.Println("t=",t)
        fmt.Println("t2=",t2)
    
        for i := 0; i < s.NumField(); i++ {
            f := s.Field(i)
            f2:= s2.Field(i)
            fmt.Printf("%d: %s %s = %v\n", i,
                typeOfT.Field(i).Name, f.Type(), f.Interface())
            fmt.Printf("%d: %s %s = %v\n", i,
                typeOfT.Field(i).Name, f2.Type(), f2.Interface())
            f2.Set(reflect.Value(f))
            fmt.Printf("%d: %s %s = %v\n", i,
                typeOfT.Field(i).Name, f2.Type(), f2.Interface())
    
        }
        fmt.Println("t=",t)
        fmt.Println("t2=",t2)
    }
    
    Output:
    
    t= {23 skidoo}
    t2= {0 }
    0: A int = 23
    0: A int = 0
    0: A int = 23
    1: B string = skidoo
    1: B string = 
    1: B string = skidoo
    t= {23 skidoo}
    t2= {23 skidoo}
    

    http://play.golang.org/p/UKFMBxfbZD

提交回复
热议问题