VOOZH about

URL: https://www.geeksforgeeks.org/go-language/golang-environment-variables/

⇱ Golang - Environment Variables - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Golang - Environment Variables

Last Updated : 4 Feb, 2021

An Environment Variable is a dynamic object pair on the Operating System. These value pairs can be manipulated with the help of the operating system. These value pairs can be used to store file path, user profile, authentication keys, execution mode, etc.

In Golang, we can use the os package to read and write environment variables.

1. Set an environment variable with os.Setenv(). This method accepts both parameters as strings. It returns an error if any.

os.Setenv(key,value) 

2. Get environment variable value with os.Getenv(). This method returns the value of the variable if the variable is present else it returns an empty value.

os.Getenv(key)

3. Delete or Unset a single environment variable using os.Unsetenv() method. This method returns an error if any.

os.Unsetenv(key)

4. Get environment variable value and a boolean with os.LookupEnv(). Boolean indicates that a key is present or not. If the key is not present false is returned.

os.LookupEnv(key)

5. List all the environment variable and their values with os.Environ(). This method returns a copy of strings, of the "key=value" format.

os.Environ()

6. Delete all environment variables with os.Clearenv().

os.Clearenv()

Example 1:

Output:

👁 Image

Example 2:

Output:

👁 Image

Example 3:
 


Output:

All environment variables cleared
Comment
Article Tags:

Explore