Go中的泛型编程。避免硬编码类型断言 [英] Generic Programming in Go. Avoiding hard coded type assertion

查看:271
本文介绍了Go中的泛型编程。避免硬编码类型断言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个通用的缓存机制,我需要在结构中设置一些属性,只知道它们的reflect.Type,属性名称和reflect.Value在属性中设置,但我无法避免类型断言,这使得我的代码不是通用的......

I'm programming a generic cache mechanism and i need to set some attributes in a struct knowing only their reflect.Type, attribute name and reflect.Value to be setted in the attribute, but i can't avoid the type assertion, that makes my code not generic...

func main() {
    addressNew := Address{"New Address description!"}

    // In the real problem, i know the reflect.Type of value, but
    // the struct came to me as a interface{}, just like this method
    // Return many kinds of values from redis as interface{}, 
    // (Customer, Order, Address, Product, SKU etc), in a generic way,
    // but returns the reflect.Type of value also.
    interfaceSomeValue := getMyValue()

    fmt.Printf("%v", interfaceSomeValue)
    fmt.Println("")

    // This portion of code comes from my cache mechanism, that is a library 
    // used by other projects. My cache lib really can't know all others
    // type structs to perform the type assertion, but the cache mechanism know 
    // the reflect.Type of the interface. 
    // If you try at this way, will cause a panic by try to access a FieldByName
    // in a interface, because the Customer comes from getMyValue and 
    // becomes a interface{}, and now a type assertion is 
    // required -> http://play.golang.org/p/YA8U9_KzC9
    newCustomerNewAttribute := SetAttribute(&interfaceSomeValue, "Local", interface{}(addressNew), reflect.TypeOf(Customer{}))

    fmt.Printf("%v", newCustomerNewAttribute)
    fmt.Println("")
}

func SetAttribute(object interface{}, attributeName string, attValue interface{}, objectType reflect.Type) interface{} {
    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 Playground解决问题(通过硬编码类型断言工作)...

Go Playground for the问题(不适用于未知界面)

推荐答案

最后,我找到了一种方法来做到这一点。按照Go Playground和以下代码片段进行操作:

Finally i find a way to do that. Follow the Go Playground and code snippet below:

GO Playground:避免硬编码类型断言


//new approach SetAttribute, without any hard coded type assertion, just based on objectType parameter
func SetAttribute(myUnknownTypeValue *interface{}, attributeName string, attValue interface{}, objectType reflect.Type) {

    // create value for old val
    oldValue := reflect.ValueOf(*myUnknownTypeValue)

    //create a new value, based on type
    newValue := reflect.New(objectType).Elem()
    // set the old value to the new one, making the 
    // implicit type assertion, not hard coding that.
    newValue.Set(oldValue)

    //set value attribute to the new struct, copy of the old one
    field := newValue.FieldByName(attributeName)
    valueForAtt := reflect.ValueOf(attValue)
    field.Set(valueForAtt)

    //capture the new value from reflect.Value
    newValInterface := newValue.Interface()
    //set the new value to the pointer
    *myUnknownTypeValue = newValInterface
}

这篇关于Go中的泛型编程。避免硬编码类型断言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆