如何从代码中获取当前的GOPATH

Ric*_*kyA 17 go

如何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

使用os.Getenv

来自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)

  • 在go 1.8中,GOPATH env var是可选的.如果用户没有它怎么办?有没有办法获得默认的?我认为go运行时应该有办法获得gopath,让Go自己为你找到它. (7认同)

rhy*_*ysd 10

你应该使用go/build包.

package main

import (
    "fmt"
    "go/build"
)

func main() {
    fmt.Println(build.Default.GOPATH)
}
Run Code Online (Sandbox Code Playgroud)