Reputation: 2026
I'm trying to embed a text file within my go application, but I can't figure out why it's not working.
I have a file named hello.txt
in the same directory as my go program, but when I compile and run the code below it doesn't print anything, when it should print the contents of hello.txt.
package main
import (
_ "embed"
"fmt"
)
// go:embed hello.txt
var hello string
func main() {
fmt.Println(hello)
}
I also tried making hello
a []byte
and even using a filesystem and listing all files, both show that there's nothing embedded.
Upvotes: 7
Views: 3792
Reputation: 2026
You cannot have a space between the //
and the go:embed
, otherwise the compiler just treats it as a comment.
The embed documentation doesn't make this clear, but it's explained in the documentation for go compile
The compiler accepts directives in the form of comments. To distinguish them from non-directive comments, directives require no space between the comment opening and the name of the directive. However, since they are comments, tools unaware of the directive convention or of a particular directive can skip over a directive like any other comment.
Upvotes: 23