To access the current GOPATH from within a Go code block, use os.Getenv:
import ( "fmt" "os" ) func main() { fmt.Println(os.Getenv("GOPATH")) }
As described in the documentation:
Getenv retrieves the value of the environment variable named by the key. It returns the value, which will be empty if the variable is not present.
Note for Go 1.8 :
In Go 1.8 and later, the default GOPATH can be accessed via go/build:
import ( "fmt" "go/build" "os" ) func main() { gopath := os.Getenv("GOPATH") if gopath == "" { gopath = build.Default.GOPATH } fmt.Println(gopath) }
The above is the detailed content of How Can I Retrieve the GOPATH from within a Go Program?. For more information, please follow other related articles on the PHP Chinese website!