Home >Backend Development >Golang >How Can I Get the Current GOPATH in Go?
Get Current GOPATH in Go Code
The Go runtime provides access to the GOROOT path, but not the GOPATH. To retrieve the current GOPATH in code, use the os.Getenv function.
import ( "fmt" "os" ) func main() { gopath := os.Getenv("GOPATH") fmt.Println(gopath) }
By default, os.Getenv searches for the environment variable "GOPATH". If it doesn't exist, the result will be an empty string.
For Go versions 1.8 and later, you can also use the go/build package to access the default GOPATH, even if it's not set in the environment:
package main 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 Get the Current GOPATH in Go?. For more information, please follow other related articles on the PHP Chinese website!