liveBook · Manning

Embed

As explained in Learn Go with Pocket-Sized Projects

The embed package is Go's standard-library package for embedding files and directories into a compiled program.

A file that does not change between runs need not be read from a runtime path. Go’s standard-library embed package can put its contents into a program at compilation time. A word corpus and an HTML template are two uses. section 8.5.2 section 11.1.2

Embed a corpus

At package scope, import `_ "embed"` and declare `//go:embed corpus/english.txt` directly above `var englishCorpus string`. The directive’s path is relative to the source `.go` file. Keep the declaration outside a function; inside one, the compiler treats the directive as an ordinary comment. The blank import retains the required package without naming one of its functions or types. section 8.5.2

//go:embed index.html
var indexPage string

The same pattern loads `index.html` into a string that can be passed to `template.New("index").Parse(indexPage)`. section 11.1.2

Choose embedding for fixed inputs, such as hardcoded values or SQL queries kept in `.sql` files. If a file must change between runs, the file-reader approach remains distinct from this compile-time choice. section 8.7 section 11.1.2

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Shows the directive, package-scope string declaration, source-relative path, and blank import; does not develop directory embedding.
Examples
Uses an embedded word-corpus file and an embedded `index.html` file parsed as a template.
What it assumes
Assumes Go variables and imports while explaining compiler directives and blank imports.
What you can do after
Apply it via Go’s embed package to load fixed file contents into package-level string variables at compilation.
How it connects
Connects compiler directives and blank imports to file loading and HTML template parsing.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.