Menu Close

Go – How to set the value of the environment variable in go

Here, We will learn how to set the value of the environment variable in go. We can do it by using Setenv() function in os package in go golang.

Function prototype:

func Setenv(key, value string) error

Paramters:

key: Environment variable name

value: To be set into variable

Return value:

Setenv() function in os package returns 
an error, if any.

Example with code:

package main

import (
  "fmt"
  "os"
  "log"
)

func main() {

  err := os.Setenv("NAME", "Jon")
 
  if err != nil {
 
    log.Fatal(err)
 
  }
 
  err = os.Setenv("ADDR", "USA")
 
  if err != nil {
 
    log.Fatal(err)
 
  }

  name := os.Getenv("NAME")

  addr := os.Getenv("ADDR")

  fmt.Printf("Name: %s, Addr: %s\n", name, addr)

}

Output:

Name: Jon, Addr: USA

To learn more about golang, Please refer given below link:

https://techieindoor.com/go-lang-tutorial/

References:

https://golang.org/doc/
https://golang.org/pkg/
Posted in golang, os, packages

Leave a Reply

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