I'm programming a generic cache mechanism and i need to set some attributes in a struct knowing only their reflect.Type, attribute Name and reflect.Value to be setted in the attribute, but i can't avoid the type assertion, that makes my code not generic...
func main() { addressNew := Address{"New Address description!"}
//in the real problem, i know the reflect.Type of value, but the struct came to me as a interface{}, just like this method
interfaceSomeValue := getMyValue()
fmt.Printf("%v", interfaceSomeValue)
fmt.Println("")
//there are any other way to perform the type assertion just knowing the reflect.Type?? My code is generic...
customer := interfaceSomeValue.(Customer) //----> here is the problem. I need to do a type assertion in a generic code...
newCustomerNewAttribute := SetAttribute(&customer, "Local", interface{}(addressNew), reflect.TypeOf(Customer{}))
fmt.Printf("%v", newCustomerNewAttribute)
fmt.Println("")
}
func SetAttribute(object interface{}, attributeName string, attValue interface{}, objectType reflect.Type) interface{} { if reflect.ValueOf(object).Kind() != reflect.Ptr { panic("need a pointer") }
value := reflect.ValueOf(object).Elem()
field := value.FieldByName(attributeName)
valueForAtt := reflect.ValueOf(attValue)
field.Set(valueForAtt)
return value.Interface()
}
Go Playground for the problem... enter link description here
Aucun commentaire:
Enregistrer un commentaire