modern-go / reflect2

reflect api without runtime reflect.Value cost
Apache License 2.0
758 stars 73 forks source link

Can not find the Struct type #18

Open zhengzepeng opened 3 years ago

zhengzepeng commented 3 years ago

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?

jinl80 commented 3 years ago

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