5/6 年后,Go 1.16(2021 年第一季度)应该会更容易,它增加了对嵌入式文件的支持(问题/提案 41191 https://github.com/golang/go/issues/41191 )
将被允许使用//go:embed
命名单个文件以初始化普通文件string
or []byte
多变的:
//go:embed gopher.png
var gopherPNG []byte
需要导入才能将文件标记为包含//go:embed
线和需要处理。
Goimports
(and gopls
等)可以学习此规则并自动在任何文件中添加导入//go:embed
如所须。
这引发了一场争论问题 42328 https://github.com/golang/go/issues/42328关于如何避免在使用时意外包含“隐藏”文件//go:embed
这已解决CL 275092 https://go-review.googlesource.com/c/go/+/275092/ and 提交 37588ff https://github.com/golang/go/commit/37588ffcb221c12c12882b591a16243ae2799fd1
决定排除文件匹配.*
and _*
嵌入整个目录树时的嵌入目录结果。
See src/embed/internal/embedtest/embed_test.go https://github.com/golang/go/blob/37588ffcb221c12c12882b591a16243ae2799fd1/src/embed/internal/embedtest/embed_test.go
//go:embed testdata/k*.txt
var local embed.FS
testFiles(t, local, "testdata/ken.txt", "If a program is too slow, it must have a loop.\n")
//go:embed testdata/k*.txt
var s string
testString(t, s, "local variable s", "If a program is too slow, it must have a loop.\n")
//go:embed testdata/h*.txt
var b []byte
testString(t, string(b), "local variable b", "hello, world\n")
注:与CL 281492 https://go-review.googlesource.com/c/go/+/281492/, cmd/go
passes embedcfg
to gccgo
如果支持的话。
另请参阅(2021 年 1 月)问题 43854 https://github.com/golang/go/issues/43854“选择加入//go:embed
to not忽略文件和空目录”。