Standard library / go/build
go/build.ImportDir()
Inspects a directory using the default build context. Expected stdout: 'demo\n'.
Formal Syntax & Structure
go syntaxgo
func ImportDir(dir string, mode ImportMode) (*Package, error)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| dir | string | Channel direction. |
| mode | ImportMode | Input to the operation as described above. |
Return Value
(*Package, error)
Inspects a directory using the default build context.
Working Example
Example Snippetgo
package main
import ( "fmt" "go/build" "os" "path/filepath")
func check(e error) { if e != nil { panic(e) }}func directory() (string, func()) { d, e := os.MkdirTemp("", "build-demo-") check(e) for n, s := range map[string]string{"base.go": "package demo\n", "only_linux.go": "package demo\n", "only_windows.go": "package demo\n", "feature.go": "//go:build feature\n\npackage demo\n"} { check(os.WriteFile(filepath.Join(d, n), []byte(s), 0600)) } return d, func() { check(os.RemoveAll(d)) }}func target() build.Context { c := build.Default c.GOOS = "linux" c.GOARCH = "amd64" c.CgoEnabled = false c.BuildTags = nil return c}
func main() { d, cleanup := directory() defer cleanup() p, e := build.ImportDir(d, 0) check(e) fmt.Println(p.Name)}