为什么go不能嵌入文件?

huangapple go评论81阅读模式
英文:

Why isn't go embedding files?

问题

我正在尝试将一个文本文件嵌入到我的Go应用程序中,但我无法弄清楚为什么它不起作用。

我在与我的Go程序相同的目录中有一个名为hello.txt的文件,但当我编译和运行下面的代码时,它不会打印任何内容,而实际上它应该打印出hello.txt的内容。

package main

import (
	_ "embed"
	"fmt"
)

// go:embed hello.txt
var hello string

func main() {
	fmt.Println(hello)
}

我还尝试将hello声明为[]byte,甚至使用文件系统并列出所有文件,但两者都显示没有嵌入任何内容。

英文:

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.

答案1

得分: 16

你不能在//go:embed之间加空格,否则编译器会将其视为注释。

embed文档没有明确说明这一点,但在go编译文档中有解释:

编译器接受以注释形式的指令。为了将其与非指令注释区分开,指令在注释开头和指令名称之间不需要空格。然而,由于它们是注释,对于不了解指令约定或特定指令的工具,可以像处理其他注释一样跳过指令。

英文:

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.

huangapple
  • 本文由 发表于 2021年12月2日 11:18:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/70193820.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定