如果您在这里运行分析包:https://github.com/frederikhors/iss-goland-invalid-type:
go run ./analysis它将印刷:
field.Name: id - field.Type: string
field.Name: name - field.Type: string
field.Name: games - field.Type: *invalid type我不明白为什么我要用*invalid type而不是*Games
代码
package main
import (
"go/types"
"golang.org/x/tools/go/packages"
)
func main() {
playerModel := LoadPackage("./player.go")
var playerStruct *types.Struct
for _, entity := range playerModel.Types.Scope().Names() {
if entity == "Player" {
playerStruct = GetStruct(entity, playerModel)
break
}
}
for i := 0; i < playerStruct.NumFields(); i++ {
field := playerStruct.Field(i)
println("field.Name: " + field.Name() + " - field.Type: " + field.Type().String())
}
}
func LoadPackage(path string) *packages.Package {
const mode = packages.NeedTypes |
packages.NeedName |
packages.NeedSyntax |
packages.NeedFiles |
packages.NeedTypesInfo |
packages.NeedTypesInfo |
packages.NeedModule
cfg := &packages.Config{Mode: mode}
pkgs, err := packages.Load(cfg, path)
if err != nil {
panic(err)
}
return pkgs[0]
}
func GetStruct(structName string, pkg *packages.Package) *types.Struct {
foundStruct := pkg.Types.Scope().Lookup(structName)
if foundStruct == nil {
return nil
}
res, _ := foundStruct.Type().Underlying().(*types.Struct)
return res
}type Player struct {
id string
name string
games *Games
}package main
type Games struct {
wins []string
losses []string
}发布于 2022-01-29 16:54:17
您只使用LoadPackage("./player.go")显式加载单个文件。并且该文件不是声明Games类型的文件。要加载有关包的所有类型的信息,您需要加载整个包。
您需要使用LoadPackage(".")。
https://stackoverflow.com/questions/70905567
复制相似问题