golang/go · error

go:embed cannot apply to var with initializer

Error message

go:embed cannot apply to var with initializer

What it means

Thrown by checkEmbed when the embedded var has an initializer (decl.Values != nil). Embedded variables are populated by the compiler from the embedded files, so supplying a value (e.g. `var x = []byte{}`) conflicts with the directive's semantics.

Source

Thrown at src/cmd/compile/internal/noder/noder.go:469

// It is called by the initialization before main is run.
// To make it unique within a package and also uncallable,
// the name, normally "pkg.init", is altered to "pkg.init.0".
var renameinitgen int

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

  1. Remove the initializer; declare the var with just its type, e.g. `var x embed.FS`.
  2. If you need default content, embed an additional fallback file rather than initializing.

Example fix

// before
//go:embed f.txt
var data = []byte{}
// after
//go:embed f.txt
var data []byte
Defensive patterns

Strategy: validation

Validate before calling

// An embed var must have a type and no initializer.
func validEmbedVar(hasType bool, hasInit bool) bool { return hasType && !hasInit }

Prevention

When it happens

Trigger: Writing `//go:embed f.txt\nvar x = []byte{}` or any var under //go:embed that includes an `=` initializer. checkEmbed sees decl.Values != nil.

Common situations: Leftover initializer from converting a normal var to an embedded one; IDE auto-complete inserting `= nil`; copy-paste from a non-embed template.

Related errors


AI-assisted analysis of golang/go@b6b368adc5 (2026-08-12). Data as JSON: /api/errors/aa8aba83b3a6a8b6. Report an issue: GitHub.