在 Go 语言中,可以使用 runtime
包中的 Caller
函数获取当前代码文件的路径,然后通过 path/filepath
包的 Dir
函数获取其所在目录。
示例代码:
package main
import (
"fmt"
"path/filepath"
"runtime"
)
func main() {
_, filename, _, ok := runtime.Caller(0)
if !ok {
fmt.Println("Failed to get current file path")
return
}
dir := filepath.Dir(filename)
fmt.Println(dir)
}
这里使用了 runtime.Caller(0)
来获取当前代码文件的路径(第一个参数为 0 表示当前函数)。然后使用 filepath.Dir
函数获取该文件所在目录。