CodeGym /행동 /Go SELF ///go:embed — files and directories embedding

//go:embed — files and directories embedding

Go SELF
레벨 44, 레슨 0
사용 가능

1. Why embed files into a binary

To be honest, the idea “let's put a file like help.txt nearby and read it” looks perfectly normal... until you try to send the program to a friend, deploy it to a server, or simply run it from another directory. Suddenly it turns out that “nearby” is a philosophical category, not a guarantee. The user runs the binary from another place, copies only the .exe, forgets assets/, and your application starts to sulk.

embed solves exactly this pain: you can embed the needed resources directly into the built binary. Then your program becomes self-contained: one file, and everything is inside. This is especially useful for CLI utilities (help texts), sample data (sample CSV/JSON), templates, static pages, and, in general, anything you want to ship together with the program.

To fix the picture in your mind, imagine a “suitcase”: a normal program often travels with a pile of packages next to it (files, directories), while with //go:embed you pack them inside the suitcase during the build stage. Not magic, but careful engineering.

2. How //go:embed works

In Go there is a special category of comments that look like comments, but for the compiler they are not just text for people. //go:embed is exactly such a case: it is a compiler directive that says “take this file/directory and put it into the binary.”

Important point: embedding happens at build time, not at run time. That is, embed is not “reading a file”, but “packing a file”. The program later no longer depends on the presence of the original help.txt on the user's disk — it simply uses what was baked into the binary.

It helps to keep a mini lifecycle diagram in mind:

flowchart LR
  A[Files in the repository
help.txt, assets/] --> B[go build] B --> C[Binary with embedded data] C --> D[Program run
files on disk may be absent]

And yes: this is still a comment. So if you miss one symbol (for example, write // go:embed with a space), the compiler will not be offended — it will simply ignore the directive, and you will be debugging “why wasn't it embedded?”

//go:embed works only for package-level variables

Now comes a rule that many people break exactly once — and remember forever.

The //go:embed directive applies only to package-level variables, that is, variables declared “outside functions.” Not inside main(), not inside init(), not inside your handlers and other wonderful places where the soul feels comfortable.

Why is that? Because embed is part of the build mechanism, and the compiler needs an “anchor”: a specific variable that always exists in the package. A local variable in a function lives only at execution time, while //go:embed must run earlier.

Here is an example that will not work (and that is good: better it does not work than works “sometimes”):

package main

import _ "embed"

func main() {
	//go:embed help.txt
	var help string // ❌ not allowed: local variable
	_ = help
}

And here is the same idea, but correct — the variable is declared at package level:

package main

import _ "embed"

//go:embed help.txt
var help string // ✅ package-level variable

func main() {
	println(len(help)) // for example: 120
}

A little later we will build this into our training application so that the help command prints help without reading from disk.

3. Choosing a type: string, []byte, or embed.FS

Before writing code, it is important to choose the “container” (receiver) where the embedded data will go. In Go, embed has three most popular options, and each is for its own scenario.

A small table to see the difference at a glance:

What we embed Variable type When it is convenient
One text file
string
help texts, templates, small configs, messages
One file as bytes
[]byte
images, binary data, “do not treat as text”
A set of files/directories
embed.FS
many resources, directory structure matters

The idea is simple: if you have one file and you know for sure it is text, use string. If it is one file, but “not necessarily text”, use []byte. If there are many files and you want to preserve the directory tree, you need embed.FS.

And yes, embed.FS is literally an “embedded file system”, which is then convenient to work with through the io/fs interfaces. Even large projects use the “add a subdirectory to the //go:embed string” approach when they need to package a set of resources together with the program.

string: embedding help.txt

Let's start with the most friendly scenario. Imagine that we have a CLI application (let's make it our training task manager), and we want tasker help to print help even if the user downloaded only the binary.

Create a file help.txt next to main.go (important: “next to” in the sense of your package sources):

Tasker — a mini task manager.

Commands:
  tasker help
  tasker version

Now in Go code we embed this file into a string variable:

package main

import (
	_ "embed"
	"fmt"
)

//go:embed help.txt
var helpText string

func main() {
	fmt.Print(helpText)
}

If you run it, you will see the file contents as program output — without os.Open, without ReadFile, without “where is help.txt on prod?”. Just printing a string.

Pay attention to the import: here it is enough to use _ "embed". We do not use any names from the embed package, but we want the compiler to “see” the //go:embed directive. This is the “import for the mechanism” pattern.

[]byte: when a file should not be treated as “text”

Now the second common case: there is a file that “could technically” be printed as a string, but that is a bad idea. For example, some binary logo, a small image, or even just data where bytes matter and not characters.

Let's make an example with an abstract file logo.bin (in practice, it can be any file). We embed it as bytes:

package main

import (
	_ "embed"
	"fmt"
)

//go:embed logo.bin
var logoBytes []byte

func main() {
	fmt.Println("logo size:", len(logoBytes)) // logo size: 256
}

Why is []byte sometimes better than string? Because in a beginner's head string very quickly becomes “this is text and it can be printed”, while printing binary data is like reading a book where QR codes are used instead of letters: technically possible, but people around you will start worrying.

embed.FS: embedding a resource directory

When there is more than one resource file, you will quickly run into an organization problem: paths, directories, different texts, templates, sample data. At that point you want to “embed everything from assets/”.

For that, embed.FS is used. Important: here you need a regular import of embed, because you are using the embed.FS type in the declaration.

package main

import "embed"

//go:embed assets/*
var assets embed.FS

At this point beginners naturally ask: “Okay, but how do I read a file from this?” Answer: through the io/fs functions and interfaces (fs.ReadFile, fs.ReadDir, etc.). But that is the next lecture: today our goal is to understand how to embed correctly and which type to choose, not how to extract it nicely.

4. Import and paths in //go:embed

embed vs _ "embed"

It is very easy to get confused by imports, so let's break it down in plain terms.

If your receiver is string or []byte, you can get by with a blank import: import _ "embed"

The logic is this: you are not using embed.FS and not calling anything from the embed package, but the compiler needs to “enable” support for the //go:embed directive in this file.

If your receiver is embed.FS, then a regular import is needed: import "embed"

Because embed.FS is a type from the embed package, and you are really referring to the name embed.

This small thing saves time in practice. Otherwise you get the classic situation: “I did everything right” → “why won't it build” → “ah, I wrote the import wrong.”

Paths in //go:embed: relative to the package

Here it is important to be gentle but firm: in //go:embed you specify not absolute operating system paths (like C:\Users\... or /home/...), but paths relative to the package, that is, relative to the directory where the file with the directive is located.

In practice this means: you usually create a clear resource folder in the project (for example, assets/ or data/) and embed from there. This disciplines you: fewer random files end up in the binary, and you clearly understand what are “resources” and what are just source files and junk.

Another human tip: treat //go:embed as a “build contract”. If you expand the pattern and accidentally embed extra stuff, the binary will grow, and you will probably not learn about it immediately. So it is better to keep resources in a separate directory from the start and embed exactly that one.

5. Mini example: tasker help without reading from disk

Now let's assemble a small piece that looks like real usefulness. We will not go deep into full command parsing (you already know that), and instead make a very simple routing by arguments.

The file help.txt already exists. In code:

package main

import (
	_ "embed"
	"fmt"
	"os"
)

//go:embed help.txt
var helpText string

func main() {
	if len(os.Args) >= 2 && os.Args[1] == "help" {
		fmt.Print(helpText)
		return
	}

	fmt.Println("unknown command, try: tasker help") // unknown command, try: tasker help
}

This is not the “final CLI architecture” (not even close), but as a learning step it is perfect: you felt the embed mechanism with your hands and got a real feature that does not depend on external files.

6. Typical mistakes when working with //go:embed

Mistake #1: trying to use //go:embed inside a function.
Almost everyone does this once, because inside main() it feels “logical”: the help text is needed here, so let's declare it here. But embed works at build time and is tied to package-level variables. A good habit is to keep embedded variables outside functions, like global package resources.

Mistake #2: wrong import — either you forgot embed, or used the wrong form.
If you are embedding into string/[]byte, the blank import _ "embed" may be enough. If you declare var x embed.FS, you need import "embed". Mix it up and you will get either a compile error about an unused import, or an unknown identifier, or “why didn't the directive work?”

Mistake #3: trying to “embed several files” into one string or []byte variable.
string and []byte are about one specific file as content. As soon as you have a set of files, the temptation appears: “let it all be one string.” In reality this quickly turns into a mess, because you lose the structure. For a set of resources, the normal path is embed.FS, that is, a tree of files in the binary.

Mistake #4: expecting embedded data to “update itself” when you changed the file.
embed bakes the contents at build time. So if you changed help.txt but did not rebuild the program, the running binary will keep the old text. This is not a bug, but a contract: embedded resources are part of the build artifact, not a “live file”.

Mistake #5: too broad a pattern and a suddenly larger binary.
It is very easy to write “embed everything,” and then discover that you accidentally packaged test data, large dumps, old images, and half your life. This hurts both the binary size and the clarity of the project. Good style is to keep resources in a separate folder and embed only that folder, as in normal large repositories where subdirectories are explicitly added in //go:embed.

1
과제
Go SELF, 레벨 44, 레슨 0
잠금
Pocket Quick Reference
Pocket Quick Reference
1
과제
Go SELF, 레벨 44, 레슨 0
잠금
바이트 로그
바이트 로그
1
과제
Go SELF, 레벨 44, 레슨 0
잠금
애셋 전시
애셋 전시
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION