mercredi 12 mai 2021

How to create an object of interface value type in go using reflection

I need to make a copy of an object in the function that gets an interface{} as a parameter

func helperFunc(param interface{}) interface{} {

    // creating parameter's object copy
    paramType := reflect.PtrTo(reflect.TypeOf(param))
    cpy := reflect.New(paramType).Elem().Interface()
    
    fillSomeValuesFunc(cpy)

    return cpy
}

The problem is that I want to make helper function for testing reading env vars function. It uses envconfig. envconfig performs two checks here:

    if s.Kind() != reflect.Ptr {
        return nil, ErrInvalidSpecification
    }
    s = s.Elem()
    if s.Kind() != reflect.Struct {
        return nil, ErrInvalidSpecification
    }

How to create the object that will pass the checks?





Aucun commentaire:

Enregistrer un commentaire