Home >Backend Development >Golang >How Can I Retrieve the GOPATH from within a Go Program?

How Can I Retrieve the GOPATH from within a Go Program?

Linda Hamilton
Linda HamiltonOriginal
2024-12-03 14:58:111069browse

How Can I Retrieve the GOPATH from within a Go Program?

Retrieving GOPATH from Code in Go

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn