reflect2
reflect2 copied to clipboard
Can not find the Struct type
Show my code.
1、utils package It define the student struct,like that:
package utils
import (
"fmt"
)
type Student struct {
Name string
}
func (s *Student) PrintName() {
fmt.Println(s.Name)
}
2、Use the Student The main function use reflect2 to find the student type,like that:
package main
import (
_ "example/testreflect/utils"
"fmt"
"github.com/modern-go/reflect2"
)
func main() {
tp := reflect2.TypeByPackageName("example/testreflect/utils", "Student")
fmt.Println(tp)
}
the output is :
<nil>
it cant find the student.
3、change the way to use the Student
package main
import (
"example/testreflect/utils"
"fmt"
"github.com/modern-go/reflect2"
)
func main() {
fmt.Println(utils.Student{})
tp := reflect2.TypeByPackageName("example/testreflect/utils", "Student")
fmt.Println(tp)
}
and the output is :
{}
utils.Student
It Works now.
So it confuse me....can anyone help?
reflect2.TypeByName("awesome-package.MyStruct") // however, if the type has not been used // it will be eliminated by compiler, so we can not get it in runtime