mardi 11 mai 2021

Initialize nil pointer when the type is interface{}

I was wondering how to initialize a nil pointer to a struct, when the initialize function receives this argument as interface{}.

How can I make this code work assuming that I will always be sending a pointer, and the type of the argument of the function is strictly interface{}?

type Foo struct {
}

func main() {
    var foo *Foo
    fmt.Println("foo is nil: ", foo)
    initialize(foo)
    fmt.Println("foo should not be nil: ", foo) // foo should be Foo{}, but it is nil
}

func initialize(fooPointer interface{}) {
    reflect.ValueOf(&fooPointer).Elem().Set(reflect.ValueOf(&Foo{}))
    fmt.Println("fooPointer is not nil: ", fooPointer)
}

https://play.golang.org/p/Va0bqXJGhWZ





Aucun commentaire:

Enregistrer un commentaire