🍃 Environment variables in Go

introduction environment variables

Environment variables are often used as a way to store the app configuration values. Instead of keeping sensitive data like passwords in a code repository, we can just set them as environment variables that the program then reads while running. In Golang’s os package, there are some functions that make it easy to set or unset environment variables, get or list environment variables, and clear environment variables.

Look at the example to compare how these functions work:

package main

import (

const userKey = "GOSAMPLES_USER"

func main() {
    // set environment variable
    err := os.Setenv(userKey, "admin")
    if err != nil {

    // get environment variable
    fmt.Printf("os.Getenv(): %s=%s\n", userKey, os.Getenv(userKey))

    // iterate over all environment variables and check if our variable is set
    for _, envStr := range os.Environ() {
        if strings.HasPrefix(envStr, userKey) {
            fmt.Printf("os.Environ(): %s environment variable is set: %s\n", userKey, envStr)

    // lookup environment variable
    val, isSet := os.LookupEnv(userKey)
    fmt.Printf("os.LookupEnv(): %s variable is set: %t, value: %s\n", userKey, isSet, val)

    // unset environment variable
    if err := os.Unsetenv(userKey); err != nil {

    // lookup environment variable again - now it should not be set
    val, isSet = os.LookupEnv(userKey)
    fmt.Printf("os.Unsetenv(); %s variable is set: %t, value: %s\n", userKey, isSet, val)

    // clear environment variables
    fmt.Printf("os.Clearenv(): number of environment variables: %d\n", len(os.Environ()))


os.Getenv(): GOSAMPLES_USER=admin
os.Environ(): GOSAMPLES_USER environment variable is set: GOSAMPLES_USER=admin
os.LookupEnv(): GOSAMPLES_USER variable is set: true, value: admin
os.Unsetenv(); GOSAMPLES_USER variable is set: false, value: 
os.Clearenv(): number of environment variables: 0

🖨️ Convert string to []byte or []byte to string in Go

Learn the difference between a string and a byte slice
introduction strings slice

🧠 Print the memory address of a variable in Go

Learn how to find and print the address of a variable or pointer
introduction pointer slice

🏟️ Capacity and length of a slice in Go

Learn what is the difference between length and capacity of a slice
introduction slice array