Can I list all standard Go packages?

GoGo Packages

Go Problem Overview


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 I want to figure out which packages are standard.

Go Solutions


Solution 1 - Go

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
}

Solution 2 - Go

Use the go list std command to list the standard packages. The special import path std expands to all packages in the standard Go library (doc).

Exec that command to get the list in a Go program:

cmd := exec.Command("go", "list", "std")
p, err := cmd.Output()
if err != nil {
	// handle error
}
stdPkgs = strings.Fields(string(p))

Solution 3 - Go

If you want a simple solution, you could check if a package is present in $GOROOT/pkg. All standard packages are installed here.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlok Kumar SinghView Question on Stackoverflow
Solution 1 - GoMartin TournoijView Answer on Stackoverflow
Solution 2 - GoBayta DarellView Answer on Stackoverflow
Solution 3 - Gosvetha.cvlView Answer on Stackoverflow