如何GOPATH从代码块中获取当前值?
runtime只有GOROOT:
// GOROOT returns the root of the Go tree.
// It uses the GOROOT environment variable, if set,
// or else the root used during the Go build.
func GOROOT() string {
s := gogetenv("GOROOT")
if s != "" {
return s
}
return defaultGoroot
}
Run Code Online (Sandbox Code Playgroud)
我可以创建一个已经GOROOT替换的函数GOPATH,但是有一个构建吗?
cod*_*eak 20
来自docs:
Getenv检索由键命名的环境变量的值.它返回值,如果变量不存在,该值将为空.
例:
package main
import (
"fmt"
"os"
)
func main() {
fmt.Println(os.Getenv("GOPATH"))
}
Run Code Online (Sandbox Code Playgroud)
Go 1.8+更新
Go 1.8具有通过go/build导出的默认GOPATH:
package main
import (
"fmt"
"go/build"
"os"
)
func main() {
gopath := os.Getenv("GOPATH")
if gopath == "" {
gopath = build.Default.GOPATH
}
fmt.Println(gopath)
}
Run Code Online (Sandbox Code Playgroud)
rhy*_*ysd 10
你应该使用go/build包.
package main
import (
"fmt"
"go/build"
)
func main() {
fmt.Println(build.Default.GOPATH)
}
Run Code Online (Sandbox Code Playgroud)