vendredi 11 décembre 2020

golang instantiate by reflection

Given a function with a parameter (that is a pointer to a struct) I want to instantiate a type of this parameter.

For example, for this function:

func MyFunction(myStruct *MyStruct) {}

using reflection I want to create a variable that contains exactly same as x := &MyStruct{} would contain.

This is the code example:

package main

import (
    "fmt"
    "reflect"
)

type MyStruct struct {
}

func main () {
    reflectedFunction := reflect.TypeOf(MyFunction)
    argType := reflectedFunction.In(0)

    reflectedParameter := reflect.New(argType)
    actual := reflectedParameter.Interface()
    fmt.Println(actual)

    expected := &MyStruct{}
    fmt.Println(expected)
}

func MyFunction(myStruct *MyStruct) {
}

If you execute it, you'll see that they contain different info:

0xc00000e028 // actual
&{} // expected

This question isn't about why I would like to do this, so please avoid recommending not doing it, etc.





Aucun commentaire:

Enregistrer un commentaire