您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

最终,我找到了一种方法。请遵循下面的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 2022/1/1 18:15:47 有632人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶