Home > OS >  How to create map in Golang with global variable as value?
How to create map in Golang with global variable as value?

Time:10-14

I have a method to check if a required environment variable exists or not, if yes then set it, else populate an error message. I am doing like the following:

package main

import (
    "errors"
    "fmt"
    "os"
    "strings"
)

var (
    AxGitDownloadUrl string
)

const ENV_ERR_MSG_START = "set the following environment variables ->"
const AX_GIT_DOWNLOAD_URL = "AX_GIT_DOWNLOAD_URL"

func main() {
    if err := verifyMandatoryEnvVarsAndSet(); err != nil {
        fmt.Printf(err.Error())
    }
}
func verifyMandatoryEnvVarsAndSet() error {
    errMsg := ENV_ERR_MSG_START
    m := map[string]string{AX_GIT_DOWNLOAD_URL: AxGitDownloadUrl}

    for k, v := range m {
        errMsg = setConfig(k, v, errMsg)
    }
    if len(errMsg) > len(ENV_ERR_MSG_START) {
        errMsg = strings.TrimSuffix(errMsg, ",")
        return errors.New(errMsg)
    }
    return nil
}

func setConfig(envVarName, globalEnvVar, errMsg string) string {
    fmt.Printf("envVarName -> %s,globalEnvVar->%s ", envVarName, globalEnvVar)
    res, ok := os.LookupEnv(envVarName)
    if ok {
        globalEnvVar = res
    } else {
        errMsg = errMsg   envVarName   ","
    }
    return errMsg
}

The problem I am facing is, in the value part of the map, it is not setting up the global variable, rather I am seeing a blank there.

So how can I set up the global variable value using the setConfig method?

Go playground link: https://go.dev/play/p/DC5oPmsjEIQ

CodePudding user response:

You can't do what you're trying to do without using pointers. The variable globalEnvVar has no connection to the global var. It's a different object located at a different address in the memory, their contents may be the same but updating one object will not update the other.

Change the map to map[string]*string and use pointers-to-variables that you want to update. And when doing the updating use pointer indirection, e.g. *globalEnvVar = res.

  •  Tags:  
  • go
  • Related