How to Use Embed in Go: Simple Guide with Examples
In Go, you use the
embed package to include files or folders directly into your program by declaring a variable with the //go:embed directive above it. This lets you access file contents as strings, byte slices, or file systems without reading files at runtime.Syntax
The embed package uses a special comment //go:embed placed just above a variable declaration. The variable must be of type string, []byte, or embed.FS. The comment lists the file or directory paths to embed.
- //go:embed <files>: Specifies files or directories to embed.
- var <name> <type>: Declares the variable to hold embedded data.
- Types:
stringfor text files,[]bytefor binary or text,embed.FSfor multiple files or directories.
go
//go:embed filename.txt var fileContent string //go:embed image.png var imageData []byte //go:embed templates/* var templates embed.FS
Example
This example shows embedding a text file and printing its content. It demonstrates how to use embed to include a file at compile time and access it as a string.
go
package main import ( "embed" "fmt" ) //go:embed hello.txt var hello string func main() { fmt.Println("Content of embedded file:") fmt.Println(hello) }
Output
Content of embedded file:
Hello, Go embed!
Common Pitfalls
- Forgetting to import
embedpackage causes compile errors. - Placing
//go:embedcomment not immediately above the variable is invalid. - Using unsupported variable types with
//go:embedcauses errors; onlystring,[]byte, andembed.FSare allowed. - Trying to embed files that do not exist or are outside the module causes build failures.
go
// Wrong: comment not immediately above variable //go:embed file.txt var data string // This will cause an error // Right: //go:embed file.txt var data string
Quick Reference
| Feature | Description | Example Type |
|---|---|---|
| Embed single file | Include one file as string or []byte | string or []byte |
| Embed multiple files | Include many files using pattern | embed.FS |
| Embed directory | Include all files in a folder | embed.FS |
| Access embedded data | Use variable directly or FS methods | variable or embed.FS.ReadFile() |
Key Takeaways
Use the //go:embed directive immediately above a variable to embed files in Go.
Variables must be string, []byte, or embed.FS to hold embedded data.
Import the embed package even if you don't call it directly.
Embedded files are included at compile time, so they must exist then.
Use embed.FS to embed multiple files or directories and access them with ReadFile.