1 回答
TA贡献1911条经验 获得超7个赞
func Set(strukt interface{}, fieldName string, newFieldValue interface{}) {
struktValueElem := reflect.ValueOf(strukt).Elem()
field := struktValueElem.FieldByName(fieldName)
newFieldValueValue := reflect.ValueOf(newFieldValue)
if field.Kind() == reflect.Ptr {
rt := field.Type() // type *A
rt = rt.Elem() // type A
rv := reflect.New(rt) // value *A
el := rv.Elem() // value A (addressable)
el.Set(newFieldValueValue) // el is addressable and has the same type as newFieldValueValue (A), Set can be used
field.Set(rv) // field is addressable and has the same type as rv (*A), Set can be used
} else { // not a pointer? more straightforward:
field.Set(newFieldValueValue)
}
}
https://play.golang.org/p/jgEK_rKbgO9
https://play.golang.org/p/B6vOONQ-RXO(紧凑)
- 1 回答
- 0 关注
- 113 浏览
添加回答
举报