Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

declare constants in golang using os.Getenv results in 'const initializer in os.Getenv("MY_SECRET") is not a constant'

If I declare constants as the following I get the error 'const initializer in os.Getenv("MY_SECRET") is not a constant'. Why is this?

New to Go and I see the return type of Getenv is a string, but I don't understand why this wouldn't work as a constant.

const (     secret     = os.Getenv("MY_SECRET")     key        = os.Getenv("MY_KEY") ) 
like image 594
Michael Avatar asked Sep 21 '17 20:09

Michael


People also ask

What is OS Getenv in Golang?

Go os. The Getenv retrieves the value of the environment variable named by the key. It returns the value, which will be empty if the variable is not present. To distinguish between an empty value and an unset value, use LookupEnv . get_env.go.

Can a struct be a const Golang?

Go does not support constants in structs. which is an invalid syntax and also has no semantic meaning. If you want to assign each game variable a game ID, you can add an unexported field to the struct, as well as a method that returns the ID value.


1 Answers

Just like the error says, a constant must have a constant value. You cannot set it to the return of a function. It must be evaluated at compile time (e.g. a string literal). If you want to store the values of environment variables looked up at run time, you'll have to store them in variables, not constants.

like image 52
Adrian Avatar answered Sep 25 '22 03:09

Adrian