实现说明
Getwd 锚定相对路径的核心是函数 main。
1 处 err != nil 分支都调用 panic(err)——第一个失败就地终止程序,而不是带着坏状态继续跑。
使用要点
- 失败路径是
panic(err)——没有可检查的错误返回值,示例里也没有任何恢复机制。 - 每一步打印都带着自己的标签:
cwd:、config:、is abs config:。
常见问题
错误处理是什么风格?
失败路径是 panic(err)——检测到的问题让运行终止,而不是被传回调用方。
运行「Getwd 锚定相对路径」会打印什么?
文件本身就是完整程序,直接运行——输出行带有 cwd:、config:、is abs config: 这类标签。
核心语句
if err != nil {
panic(err)
}
代码示例
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
// 进程启动目录是相对路径的锚点
cwd, err := os.Getwd()
if err != nil {
panic(err)
}
fmt.Println("cwd:", cwd)
// 用 Join 而不是手写 "/":跨平台且自动清理多余分隔符
config := filepath.Join(cwd, "config", "app.yaml")
fmt.Println("config:", config)
fmt.Println("is abs config:", filepath.IsAbs(config))
// 对照:不含 cwd 的 Join 只做清理与拼接,结果仍是相对路径,
// 不依赖也不锚定 cwd——变abs与否取决于是否以分隔符开头
relativePath := filepath.Join("etc", "app.yaml")
fmt.Println("relative join:", relativePath)
fmt.Println("is abs relativePath:", filepath.IsAbs(relativePath))
}