Reputation: 588
I have a map with value of type interface.Also I want to use this map key,val for change value in another func with reflect.
func main(){
ValueForUpdate := make(map[string]interface{})
ValueForUpdate["DeliveryCount"] = 2 //type int
ValueForUpdate["BulkId"] = "100200300" //type string
UpdateSendTBL(ValueForUpdate)
}
func UpdateSendTBL(keyNewVal map[string]interface{}){
get := // some data
rowValue := reflect.ValueOf(get).Elem()
for key, val := range keyNewVal {
fieldValue := rowValue.FieldByName(key)
if fieldValue.Type().String() == "string" {
fieldValue.SetString(val)
}else if fieldValue.Type().String() == "int"{
fieldValue.SetInt(val)
}
}
}
but this error :
cannot use val (type interface {}) as type int64 in argument to fieldValue.SetInt: need type assertion
cannot use val (type interface {}) as type string in argument to fieldValue.SetString: need type assertion
Upvotes: 3
Views: 2814
Reputation: 353
You need to make use of type assertion, change the code as below:
if fieldValue.Type().String() == "string" {
fieldValue.SetString(val.(string))
}else if fieldValue.Type().String() == "int"{
fieldValue.SetInt(val.(int64))
}
Upvotes: 1