Go中的通用编程。避免硬编码类型断言

Go中的通用编程。避免硬编码类型断言,第1张

Go中的通用编程。避免硬编码类型断言

最终,我找到了一种方法。请遵循下面的Go Playground和代码段:

前往游乐场:避免硬编码类型声明

//new approach SetAttribute, without any hard pred type assertion, just based on objectType parameterfunc 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}


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/4895070.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-12
下一篇2022-11-12

发表评论

登录后才能评论

评论列表(0条)

    保存