reflect2 icon indicating copy to clipboard operation
reflect2 copied to clipboard

Can not find the Struct type

Open zhengzepeng opened this issue 5 years ago • 1 comments

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?

zhengzepeng avatar Feb 26 '21 03:02 zhengzepeng

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

jinl80 avatar Mar 10 '21 09:03 jinl80