Welcome To Golang By Example

Menu
  • Home
  • Blog
Menu

List all env variables in Go

Posted on February 22, 2023March 16, 2023 by admin

Table of Contents

  • Overview
  • Code:

Overview

os package provides an Environ() function to get the list all environment variables.

  • Get all the env variables. It returns an array of string.
func Environ() []string 

There is also a way to clear all the env variables. Clearenv() function can be used to achieve the same.

func Clearenv()

Code:

package main
import (
"fmt"
"log"
"os"
)
func main() {
//Set env a to b
err := os.Setenv("a", "b")
if err != nil {
log.Fatal(err)
}
err = os.Setenv("c", "d")
if err != nil {
log.Fatal(err)
}
//Get all env variables
fmt.Println(os.Environ())
//Clear all env variables
os.Clearenv()
//Again get all env variable
fmt.Println(os.Environ())
}

Output:

List of all env varialbes on your system including a and b

Popular Articles

Golang Comprehensive Tutorial Series

All Design Patterns in Go (Golang)

Slice in golang

Variables in Go (Golang) – Complete Guide

OOP: Inheritance in GOLANG complete guide

Using Context Package in GO (Golang) – Complete Guide

All data types in Golang with examples

Understanding time and date in Go (Golang) – Complete Guide

©2023 Welcome To Golang By Example | Design: Web XP