0
0
GoHow-ToBeginner · 3 min read

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: string for text files, []byte for binary or text, embed.FS for 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 embed package causes compile errors.
  • Placing //go:embed comment not immediately above the variable is invalid.
  • Using unsupported variable types with //go:embed causes errors; only string, []byte, and embed.FS are 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

FeatureDescriptionExample Type
Embed single fileInclude one file as string or []bytestring or []byte
Embed multiple filesInclude many files using patternembed.FS
Embed directoryInclude all files in a folderembed.FS
Access embedded dataUse variable directly or FS methodsvariable 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.