Go by Example: Environment Variables

package main

import (
	"fmt"
	"os"
)

func main() {
	os.Setenv("FOO", "1")
	fmt.Println("FOO:", os.Getenv("FOO"))
	fmt.Println("BAR:", os.Getenv("BAR"))

	fmt.Println()
	for _, e := range os.Environ() {
		fmt.Println(e)
	}
}

In this example, the os package’s Setenv and Getenv functions are used to set and get an environment variable named FOO. The os.Environ function returns a slice of strings representing all environment variables, which are then printed out.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *