在 Go 中获取当前路径的方法有两种:使用 os.Getwd 返回当前工作目录的绝对路径。使用 path/filepath.Abs 返回指定路径的绝对路径,即使指定了相对路径。

在 Go 中获取当前路径
在 Go 中获取当前路径有两种方法:
1. 使用 os.Getwd
<code class="go">package main
import (
"fmt"
"os"
)
func main() {
wd, err := os.Getwd()
if err != nil {
fmt.Println(err)
return
}
fmt.Println("Current working directory:", wd)
}</code>2. 使用 path/filepath.Abs
立即学习“go语言免费学习笔记(深入)”;
<code class="go">package main
import (
"fmt"
"path/filepath"
)
func main() {
wd, err := filepath.Abs(".")
if err != nil {
fmt.Println(err)
return
}
fmt.Println("Current working directory:", wd)
}</code>示例输出:
<code>Current working directory: /Users/username/projects/my_project</code>
解释:
os.Getwd 函数返回当前工作目录的绝对路径。path/filepath.Abs 函数返回指定路径的绝对路径。在我们的例子中,. 代表当前目录。注意事项:
os.Getwd 将返回 ""。path/filepath.Abs 返回的路径始终是绝对路径,即使指定了相对路径。以上就是golang怎么获取当前路径的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号