Go Embedded Files
Embedded files are files whose contents the compiler packs into the program at build time. A //go:embed line above a variable names the file that fills it.
Embedding a greeting
The //go:embed line names hello.txt. The string variable greeting starts with the text from that file.
package main
import (
_ "embed"
"fmt"
)
//go:embed hello.txt
var greeting string
func main() {
fmt.Print(greeting)
}Embedding as bytes
The same line above a byte slice stores the file as bytes. The length shows the byte count, and the text prints after it.
package main
import (
_ "embed"
"fmt"
)
//go:embed banner.txt
var banner []byte
func main() {
fmt.Println(len(banner))
fmt.Print(string(banner))
}Choosing between two files
Two variables hold two embedded files. A stored number picks which text prints.
package main
import (
_ "embed"
"fmt"
)
//go:embed one.txt
var first string
//go:embed two.txt
var second string
func main() {
pick := 2
if pick == 1 {
fmt.Print(first)
} else {
fmt.Print(second)
}
}Example
package main
import (
_ "embed"
"fmt"
)
//go:embed appetizer.txt
var appetizer string
//go:embed dessert.txt
var dessert string
func main() {
fmt.Println("Menu:")
fmt.Print(appetizer)
fmt.Print(dessert)
}Key points
- The //go:embed line sits directly above the variable it fills.
- An embedded file can fill a string variable or a byte slice variable.
- The named file must sit beside the source file when the program builds.
- The contents are fixed at build time, so a running program never opens the file.
In this example, two short files are embedded as strings. Main prints a menu heading first. It then prints the two notes one after the other.
Note
Changing an embedded file means building the program again, because the old build holds the old contents.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Go Playground
Exercise
When does the content of an embedded file enter the program?