Listing Packages To list packages in your workspace, go to your workspace folder and run this command: go list ./... ./ tells to start from the current folder, ... tells to go down recursively.
As we discussed, there are two types of packages. An executable package and a utility package. An executable package is your main application since you will be running it.
The Go standard library is a set of core packages that enhance and extend the language. These packages add to the number of different types of programs you can write without the need to build your own packages or download packages others have published.
Your first program. The first statement in a Go source file must be package name . Executable commands must always use package main .
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
}
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))
If you want a simple solution, you could check if a package is present in $GOROOT/pkg. All standard packages are installed here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With