如何理解Golang中的”path.Match”中的”非分隔符字符”?

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

how to understand golang "non-Separator characters" at path.Match

问题

当我使用golang的embed包时,我对路径匹配感到困惑。*代表什么?

官方称之为非分隔符字符

在这里:https://pkg.go.dev/path/filepath#Match

'*'匹配任何非分隔符字符的序列

起初,我理解为非分隔符字符指的是正斜杠(前导斜杠/),但下面的示例表明情况并非如此。

# 目录树
├── stubs
│   ├── hello.txt
│   └── xyz
│       └── zyx.txt
└── hello.go
# 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)
}

然后运行go run hello.go将成功执行。

这个例子告诉我*可以匹配/

非分隔符字符是什么意思?

感谢解释。

英文:

When I use golang's embed package, I encounter confusion about path matching. that's what * refers to?

Officially called non-Separator characters

Here: https://pkg.go.dev/path/filepath#Match

'*' matches any sequence of non-Separator characters

At first I understood non-Separator characters meant forward slashes(leading slash /), but the following example shows that this is not the case.

# 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)
}

Then run go run hello.go will execute successfully.

This case tell me * can match /.

what does non-Separator characters mean?

Thanks for the explanation.

答案1

得分: 1

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文件系统中。

英文:

T2.ReadFile("stubs/xyz/zyx.txt") works for a different reason than you think.

The documentation for go:embed explains:

> If a pattern names a directory, all files in the subtree rooted at
> that directory are embedded (recursively), except that files with
> names beginning with ‘.’ or ‘_’ are excluded.

https://pkg.go.dev/embed#hdr-Directives

You have declared T2 as:

//go:embed stubs*
var T2 embed.FS

The pattern stubs* matches the directory stubs, so the whole directory stubs, including all files in it (recursively) are included in the T2 filesystem.

huangapple
  • 本文由 发表于 2022年12月11日 12:33:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/74758376.html
匿名

发表评论

匿名网友

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

确定