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

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

    Use reflect.ValueOf() to convert to concrete type. After that you could use reflect.Value.SetString to set the value you want.

    structValue := FooBar{Foo: "foo", Bar: 10}
    fields := reflect.TypeOf(structValue)
    values := reflect.ValueOf(structValue)
    
    num := fields.NumField()
    
    for i := 0; i < num; i++ {
        field := fields.Field(i)
        value := values.Field(i)
        fmt.Print("Type:", field.Type, ",", field.Name, "=", value, "\n")
    
        switch value.Kind() {
        case reflect.String:
            v := value.String()
            fmt.Print(v, "\n")
        case reflect.Int:
            v := strconv.FormatInt(value.Int(), 10)
            fmt.Print(v, "\n")
        case reflect.Int32:
            v := strconv.FormatInt(value.Int(), 10)
            fmt.Print(v, "\n")
        case reflect.Int64:
            v := strconv.FormatInt(value.Int(), 10)
            fmt.Print(v, "\n")
        default:
            assert.Fail(t, "Not support type of struct")
        }
    }
    

提交回复
热议问题