Standard library / go/build

go/build.ImportComment

Checks import comments and records the declared import path. Expected stdout: 'example.invalid/demo\n'.

Formal Syntax & Structure

go syntaxgo
const ImportComment ImportMode = 4

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()  check(os.WriteFile(filepath.Join(d, "base.go"), []byte("package demo // import \"example.invalid/demo\"\n"), 0600))  c := target()  p, e := c.ImportDir(d, build.ImportComment)  check(e)  fmt.Println(p.ImportComment)}
Go Reference