猿问

为什么这是 `*invalid type` 而不是 `*Games`?

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


代码

分析/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

}

游戏.go:

package main


type Games struct {

    wins   []string

    losses []string

}


qq_花开花谢_0
浏览 111回答 1
1回答

慕侠2389804

您仅使用LoadPackage("./player.go").&nbsp;并且该文件不是声明类型的文件Games。要加载有关所有类型包的信息,您需要加载整个包。你需要使用LoadPackage(".").
随时随地看视频慕课网APP

相关分类

Go
我要回答