乐闻世界logo
搜索文章和话题

Where are the golang environment variables stored?

1个答案

1

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:

go
package 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:

go
package 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:

go
package 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.

2024年7月26日 01:01 回复

你的答案