【问题标题】:Generic Programming in Go, Implicit generic typeGo 中的泛型编程,隐式泛型类型
【发布时间】:2015-06-02 03:13:52
【问题描述】:

我需要 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

【问题讨论】:

    标签: generics reflection go


    【解决方案1】:

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

    如果你直接使用对象,它会恐慌,因为你获取的是接口的地址,而不是客户。

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

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

    【讨论】:

    猜你喜欢
    • 2018-11-21
    • 2013-11-15
    • 2015-01-19
    • 1970-01-01
    • 2016-02-22
    • 2015-08-15
    • 1970-01-01
    • 1970-01-01
    • 2015-11-28
    相关资源
    最近更新 更多