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


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 (

func main() {

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

  name := os.Getenv("NAME")

  addr := os.Getenv("ADDR")

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



Name: Jon, Addr: USA

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

Posted in golang, os, packages

Leave a Reply

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