jeudi 22 juillet 2021

Different behave of usual struct and struct created by reflection golang

I need a pointer to a struct for function that fills struct's fields. An usual expression a = &A{} has type *main.A and works perfect. Another way is to create an empty struct with reflect:

type A struct {
    Name string
}

a2 := reflect.New(reflect.TypeOf((*A)(nil)).Elem()).Elem().Interface()
a2_ := &a2
fmt.Printf("a2 type : %T\na2Ptr type : %T\n", a2, a2_) //OUTPUT: main.A; *interface{}

So a and a2 have same type main.A. But theirs pointers have different type (*main.A and *interface{}). Why do a and a2 behave differently when i point them despite the same type? How to make their behave the same?

Function that accepts pointer to a struct: https://play.golang.org/p/Jt1Z6a3ZRMR





Aucun commentaire:

Enregistrer un commentaire