I have 2 different packages(pkg1, pkg2), in first i have code that calls function from another package
file#1
package pkg1
import "pkg2"
import "reflect"
type User struct {
name string
...
}
func main() {
fmt.Println(reflect.TypeOf((*User)(nil)) //=> *User
pkg2.RegisterStruct(reflect.TypeOf((*User)(nil))
//pkg2.RegisterStruct(reflect.TypeOf(&User{}) // also tried this way
}
file#2
package pkg2
import "reflect"
func RegisterStruct(u interface{}) { // also tried to have argument type as reflect.Type
fmt.Println(u) //=> *reflect.rtype
}
Why type was reflect.rtype
instead of *User
? And how do i correctly pass type to another pkg?
The reflect.TypeOf()
returns a reflect.Type
now you are doing two completely different things with: In the first call to Println (the "correct" one) this reflect.Type
is wrapped inside an interface{}
(during the call to Println) while in the second (the "wrong" one) you wrap the reflect.Type
inside an interface{}
while calling RegisterSturct and you then rewrap it once more inside an additional interface{}
while calling Println. Println just removes one layer of interface{}-wrapping.