golang/go · error
go:embed cannot apply to var inside func
Error message
go:embed cannot apply to var inside func
What it means
Thrown by checkEmbed when the embedded var declaration appears inside a function body (withinFunc == true). //go:embed only operates on package-level variables because the embed mechanism runs at compile time and populates package initializers, which cannot be local.
Source
Thrown at src/cmd/compile/internal/noder/noder.go:474
func Renameinit() *types.Sym {
s := typecheck.LookupNum("init.", renameinitgen)
renameinitgen++
return s
}
func checkEmbed(decl *syntax.VarDecl, haveEmbed, withinFunc bool) error {
switch {
case !haveEmbed:
return errors.New("go:embed requires import \"embed\" (or import _ \"embed\", if package is not used)")
case len(decl.NameList) > 1:
return errors.New("go:embed cannot apply to multiple vars")
case decl.Values != nil:
return errors.New("go:embed cannot apply to var with initializer")
case decl.Type == nil:
// Should not happen, since Values == nil now.
return errors.New("go:embed cannot apply to var without type")
case withinFunc:
return errors.New("go:embed cannot apply to var inside func")
case !types.AllowsGoVersion(1, 16):
return fmt.Errorf("go:embed requires go1.16 or later (-lang was set to %s; check go.mod)", base.Flag.Lang)
default:
return nil
}
}
View on GitHub (pinned to b6b368adc5)
Solutions
- Move the var (and its //go:embed directive) to package scope.
- Access the package-level embedded value from within the function.
Example fix
// before
func load() {
//go:embed f.txt
var data []byte
_ = data
}
// after
//go:embed f.txt
var data []byte
func load() { _ = data } Defensive patterns
Strategy: validation
Validate before calling
// Ensure embed vars are declared at package scope, not inside a func.
func embedAtPackageScope(isInsideFunc bool) bool { return !isInsideFunc } Prevention
- Keep //go:embed directives on package-level vars only.
- Access package-level embedded data from within functions instead of re-declaring locally.
- Review refactors that move vars into functions for locality.
When it happens
Trigger: Placing a `//go:embed` directive above a var declared inside a func. checkEmbed is called with withinFunc==true.
Common situations: Trying to embed a file per-function-call for scoped access; refactoring that moved an embedded var into a function; misunderstanding that embed is a package-level facility.
Related errors
- go:embed requires import "embed" (or import _ "embed", if pa
- go:embed cannot apply to multiple vars
- go:embed cannot apply to var with initializer
- go:embed cannot apply to var without type
- failed to locate cmd/compile for target platform
AI-assisted analysis of golang/go@b6b368adc5 (2026-08-12).
Data as JSON: /api/errors/6b8a6d02faeb40bb.
Report an issue: GitHub.