Juliatzin
Juliatzin

Reputation: 19695

set a variable once for the whole golang project

I need to have a variable volume_path for my project.

volume_path is set in .env file, so I have 2 definition for it:

.env
.env.testing

In my code, I will set the var to:

var Volume_path = os.Getenv("VOLUME_PATH")

I know how to do it to set this var in each file, but I would like to define it just once, and make it accesible for all the project, is it possible ?

Upvotes: 1

Views: 654

Answers (1)

icza
icza

Reputation: 417777

Simply use a single variable, and refer to that single instance from everywhere you need it.

Note that you can't refer to identifiers defined in the main package from other packages. So if you have multiple packages, this variable must be in a non-main package. Put it in package example, have it start with an uppercase letter (so it is exported), and import the example package from other packages, and you can refer to it as example.Volume_path.

Also note that the Volume_path name is not idiomatic in Go, you should name it rather VolumePath.

example.go:

package example

var VolumePath = os.Getenv("VOLUME_PATH")

And in other packages:

import (
    "path/to/example"
    "fmt"
)

func something() {
    fmt.Println(example.VolumePath)
}

Upvotes: 1

Related Questions