Environment Variables
This Go program demonstrates how to work with environment variables using the os
package. It sets the value of the "FOO" environment variable, retrieves its value, and prints all environment variables. Let's break down the code with inline comments:
Explanation:
Setting Environment Variable:
The program uses
os.Setenv
to set the value of the "FOO" environment variable to "1".
Retrieving Environment Variable Value:
It uses
os.Getenv
to retrieve and print the value of the "FOO" environment variable.
Checking for Unset Environment Variable:
It retrieves and prints the value of the "BAR" environment variable, which is not set. This will print an empty string.
Printing All Environment Variables:
The program uses
os.Environ
to retrieve all environment variables and then iterates through them.For each environment variable, it splits the key-value pair and prints the name of the environment variable.
You can run the program to see the values of the "FOO" and "BAR" environment variables, as well as all other environment variables set in your system:
Last updated
Was this helpful?