[Solved] Generic Programming in Go. Avoiding hard coded type assertion


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

GO Playground: Avoiding Hard Coded Type Assertion


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

solved Generic Programming in Go. Avoiding hard coded type assertion