Wednesday, January 17, 2018

go lang get struct field value by field name through reflect method

What
i want to used go lang reflect method to get struct field value by dynamic reflect.

How
func getStructFieldSimple(v interface{}, field string) interface{} {

    if v == nil || field == "" {
        return nil
    }

    val := reflect.ValueOf(v)

    if val.Kind() == reflect.Ptr {
        val = val.Elem()
    }

    field = strings.ToLower(field)

    c := val.NumField()
    for i := 0; i < c; i++ {
        valueField := val.Field(i)
        typeField := val.Type().Field(i)

        if strings.ToLower(typeField.Name) == field {
            return valueField.Interface()
        }

        // tag := typeField.Tag
        // fmt.Printf("Field Name: %s,\t Field Value: %v,\t Tag Value: %s\n", typeField.Name, valueField.Interface(), tag.Get("tag_name"))
    }
    return nil
}
Last
Thanks!

No comments: