当我使用golang的嵌入包时,我遇到了关于路径匹配的困惑。这就是*
所指的?
正式名称non-Separator characters
: https://pkg.go.dev/path/filepath匹配
'*' matches any sequence of non-Separator characters
起初我理解non-Separator characters
是指正斜杠(前斜杠/
),但下面的例子表明情况并非如此。
# dir tree
├── stubs
│ ├── hello.txt
│ └── xyz
│ └── zyx.txt
└── hello.go
# source file for hello.go
package main
import "embed"
//go:embed stubs/*
var T1 embed.FS
//go:embed stubs*
var T2 embed.FS
func main() {
s, e := T1.ReadFile("stubs/hello.txt")
fmt.Println(string(s))
fmt.Println(e)
s, e = T2.ReadFile("stubs/xyz/zyx.txt")
fmt.Println(string(s))
fmt.Println(e)
}
rungo run hello.go
将执行成功。
这个例子告诉我*
可以匹配/
。
non-Separator characters
是什么意思?
谢谢你的解释。
T2.ReadFile("stubs/xyz/zyx.txt")
起作用的原因与你想象的不同。
go:embed
的文档解释:
如果一个模式命名了一个目录,那么子树中的所有文件都扎根于该目录被嵌入(递归地),除了带有以'开头的名字。'或' _ '除外。
https://pkg.go.dev/embed hdr-Directives
您已将T2
声明为:
//go:embed stubs*
var T2 embed.FS
模式stubs*
匹配目录stubs
,因此整个目录stubs
,包括其中的所有文件(递归地)都包含在T2
文件系统中。