为什么这是"*无效类型"而不是"*游戏"



如果在此处运行分析包: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

代码

  • analysis/main.go:
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
}
  • 播放器.go:
type Player struct {
id    string
name  string
games *Games
}
  • games.go:
package main
type Games struct {
wins   []string
losses []string
}

您只显式加载带有LoadPackage("./player.go")单个文件。并且该文件是而不是声明Games类型的文件。要加载所有类型包的信息,您需要加载整个包。

您需要使用LoadPackage(".")

相关内容

  • 没有找到相关文章

最新更新