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
Release: 2024-12-03 14:58:11
Original
966 people have browsed it

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"))
}
Copy after login

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)
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template