dongpouda6700 2015-06-01 18:47 采纳率: 100%
浏览 52
已采纳

Go中的泛型编程,隐式泛型

I need Go to implicitly resolve my struct type, in order to do generic replacement of some attribute.

//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()
}

Please check out full example in the Go playground... http://play.golang.org/p/jxxSB5FKEy

  • 写回答

1条回答 默认 最新

  • donglu1971 2015-06-01 19:05
    关注

    convertedObject is the value of what is in the object interface. Taking the address of that has no effect on the original customer. (and converted is probably a poor prefix for the name, since that is generated from a "type assertion", not a "type conversion")

    If you use object directly, it panics, because you're then taking the address of the interface, not the customer.

    You need to pass the address of the customer you want to modify to the function:

    SetAttribute(&customer, "Local", addressNew, reflect.TypeOf(Customer{}))
    

    You can also have your SetAttribute check if it's a pointer first:

    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()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算