Can I list all standard Go packages?

后端 未结 3 1667
挽巷
挽巷 2021-01-31 23:56

Is there a way in Go to list all the standard/built-in packages (i.e., the packages which come installed with a Go installation)?

I have a list of packages and

3条回答
  •  醉酒成梦
    2021-02-01 00:38

    You can use the new golang.org/x/tools/go/packages for this. This provides a programmatic interface for most of go list:

    package main
    
    import (
        "fmt"
    
        "golang.org/x/tools/go/packages"
    )
    
    func main() {
        pkgs, err := packages.Load(nil, "std")
        if err != nil {
            panic(err)
        }
    
        fmt.Println(pkgs)
        // Output: [archive/tar archive/zip bufio bytes compress/bzip2 ... ]
    }
    

    To get a isStandardPackage() you can store it in a map, like so:

    package main
    
    import (
        "fmt"
    
        "golang.org/x/tools/go/packages"
    )
    
    var standardPackages = make(map[string]struct{})
    
    func init() {
        pkgs, err := packages.Load(nil, "std")
        if err != nil {
            panic(err)
        }
    
        for _, p := range pkgs {
            standardPackages[p.PkgPath] = struct{}{}
        }
    }
    
    func isStandardPackage(pkg string) bool {
        _, ok := standardPackages[pkg]
        return ok
    }
    
    func main() {
        fmt.Println(isStandardPackage("fmt"))  // true
        fmt.Println(isStandardPackage("nope")) // false
    }
    

提交回复
热议问题