Standard library / go/build
go/build.Context.MatchFile()
Reports whether a source file matches the configured target and build tags. Expected stdout: 'true false\n'.
Formal Syntax & Structure
go syntaxgo
func (ctxt *Context) MatchFile(dir, name string) (match bool, err error)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| dir | string | Channel direction. |
| name | string | Name of the symbol or package. |
Return Value
(match bool, err error)
Reports whether a source file matches the configured target and build tags.
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() c := target() a, e := c.MatchFile(d, "only_linux.go") check(e) b, e := c.MatchFile(d, "only_windows.go") check(e) fmt.Println(a, b)}