英文:
Passing argument to filepath.Glob function in GoLang
问题
我已经尝试了几天来学习Go语言,并且我正在尝试编写一个简单的程序,用于匹配特定目录中的特定文件。然而,我不知道如何将变量传递给filepath.Glob函数。
我的尝试:
func ReadDirectory(srcDir string) {
files, _ := filepath.Glob("[a-Z0-9]")
fmt.Println(files)
}
这段代码可以打印出我运行程序时的当前目录。然而,我正在寻找一种方法来将srcDir变量传递给它,这样我就可以从任何目录中找到文件。
英文:
I've been trying to get my head around with GoLang for few days and I am trying to make simple program which matches to certain files in certain directory. However I don't know how to pass variable to filepath.Glob function.
My attempt:
func ReadDirectory(srcDir string) {
files, _ := filepath.Glob("[a-Z0-9]")
fmt.Println(files)
}
This one prints well current directory where I am running the program. However I am looking for a way to list pass srcDir variable to it so I can find files from whatever directory.
答案1
得分: 9
只需在模式前加上目录:
files, _ := filepath.Glob(srcDir + "/[a-Z0-9]")
文档给出了以下示例:
模式可以描述层次结构的名称,例如
/usr/*/bin/ed
(假设分隔符为/
)。
英文:
Just prefix the pattern with the directory:
files, _ := filepath.Glob(srcDir + "/[a-Z0-9]")
The docs give this example:
> The pattern may describe hierarchical names such as /usr/*/bin/ed
(assuming the Separator is /
).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论