go - Go 中的泛型编程,隐式泛型类型

标签 go reflection

我需要 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 Playground 中的完整示例... http://play.golang.org/p/jxxSB5FKEy

最佳答案

convertedObjectobject 接口(interface)中的值。获取地址对原始 customer 没有影响。 (并且 converted 可能是名称的不良前缀,因为它是从“类型断言”而不是“类型转换”生成的)

如果您直接使用对象,它会崩溃,因为您随后获取的是接口(interface)的地址,而不是客户的地址。

需要将要修改的客户地址传递给函数:

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 - Go 中的泛型编程,隐式泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30580941/

相关文章:

golang 模板不适用于 httprouter

java - 使用 hibernate 持久抛出的反射调用方法 object.getId() 抛出lazyInitializeException

c# - 如何使用参数获取 Ctor 的 ConstructorInfo

c# - 为什么 Reflection 的 GetProperty() 或 GetField() 不是实例或扩展方法?

scala - 结构类型细化和类型相等

arrays - 使用的变量。但错误仍然是 "variable x not used"

go - 如何在 Golang 中借助标志使用随机参数

go - 无法根据 Golang 中的条件将接口(interface)转换为结构

multithreading - Go 是否可以在不为每个外部进程启动一个 OS 线程的情况下生成并与外部进程通信?

c# - PropertyInfo 到 Expression<Func<TModel, TProperty>>