1

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 ?

6
  • Then simply have one "instance" of this variable, and refer to this single instance everywhere. What is the problem? Commented Jan 29, 2019 at 9:20
  • I started coding go 2 weeks ago :) I tried to define it in main.go and refer it in other package, but I can't import main module to access it Commented Jan 29, 2019 at 9:25
  • package main is importable only in special cases, put your variable in a non-main package and import that one. Commented Jan 29, 2019 at 9:26
  • Just a thought but is os.Getenv("VOLUME_PATH") really so long to write compared to importing a variable from another file? Commented Jan 29, 2019 at 9:31
  • It would have been cleaner to have a VolumePath var, but I have no central package other than main, so, I guess I will do it like that... Commented Jan 29, 2019 at 9:40

1 Answer 1

1

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)
}
Sign up to request clarification or add additional context in comments.

1 Comment

@JuliatzindelToro Yes, package main is special in many ways. Don't try to learn the language by drawing conclusions regarding to it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.