Go 中的泛型编程,隐式泛型类型
Generic Programming in Go, Implicit generic type
我需要 Go 来隐式解析我的结构类型,以便对某些属性进行通用替换。
//must replace the attribute with attValue
func SetAttribute(object interface{}, attributeName string, attValue interface{}, objectType reflect.Type) interface{} {
/// works perfectly, but function SetAttribute needs to know Customer type to do the convertion
convertedObject := object.(Customer) // <-- Need to hard code a cast :(
// doesn't works... raise panic!
//convertedObject := object
value := reflect.ValueOf(&convertedObject).Elem()
field := value.FieldByName(attributeName)
valueForAtt := reflect.ValueOf(attValue)
field.Set(valueForAtt)
return value.Interface()
}
请查看 Go 游乐场中的完整示例...
http://play.golang.org/p/jxxSB5FKEy
convertedObject
是object
界面中的值。取那个的地址对原来的customer
没有影响。 (并且 converted 可能是名称的不良前缀,因为它是从 "type assertion" 而不是 "type conversion" 生成的)
如果您直接使用对象,它会出现混乱,因为您随后获取的是接口的地址,而不是客户的地址。
您需要将要修改的客户地址传递给函数:
SetAttribute(&customer, "Local", addressNew, reflect.TypeOf(Customer{}))
您还可以让 SetAttribute 先检查它是否是一个指针:
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 来隐式解析我的结构类型,以便对某些属性进行通用替换。
//must replace the attribute with attValue
func SetAttribute(object interface{}, attributeName string, attValue interface{}, objectType reflect.Type) interface{} {
/// works perfectly, but function SetAttribute needs to know Customer type to do the convertion
convertedObject := object.(Customer) // <-- Need to hard code a cast :(
// doesn't works... raise panic!
//convertedObject := object
value := reflect.ValueOf(&convertedObject).Elem()
field := value.FieldByName(attributeName)
valueForAtt := reflect.ValueOf(attValue)
field.Set(valueForAtt)
return value.Interface()
}
请查看 Go 游乐场中的完整示例... http://play.golang.org/p/jxxSB5FKEy
convertedObject
是object
界面中的值。取那个的地址对原来的customer
没有影响。 (并且 converted 可能是名称的不良前缀,因为它是从 "type assertion" 而不是 "type conversion" 生成的)
如果您直接使用对象,它会出现混乱,因为您随后获取的是接口的地址,而不是客户的地址。
您需要将要修改的客户地址传递给函数:
SetAttribute(&customer, "Local", addressNew, reflect.TypeOf(Customer{}))
您还可以让 SetAttribute 先检查它是否是一个指针:
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()