In Go, environment variables are not managed by Go itself; they are stored in the operating system. Go provides standard library functions, primarily in the os package, for retrieving and setting environment variables.
Retrieving Environment Variables
To retrieve environment variables, use the os.Getenv() function. For example, to get the value of the PATH environment variable, use the following code:
gopackage main import ( "fmt" "os" ) func main() { path := os.Getenv("PATH") fmt.Println("PATH:", path) }
Setting Environment Variables
To set environment variables at runtime, use os.Setenv(). For example, to set a new environment variable MY_VAR:
gopackage main import ( "fmt" "os" ) func main() { os.Setenv("MY_VAR", "12345") myVar := os.Getenv("MY_VAR") fmt.Println("MY_VAR:", myVar) }
Listing All Environment Variables
To list all environment variables, use os.Environ(), which returns a slice containing all environment variables in key=value format:
gopackage main import ( "fmt" "os" ) func main() { envs := os.Environ() for _, env := range envs { fmt.Println(env) } }
This covers the basic methods for using environment variables in Go. These environment variables are set by the operating system before the process runs and are accessed and manipulated through Go's os package.