Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global variable private to file

Tags:

In GOLANG, Is there a way to make a variable's scope local to a file within a package? In my case, there are 2 files ex1.go and ex02.go. ex01.go defines a global variable

var wg sync.WaitGroup 

which is used across functions in that file.

In another file ex02.go (which has no relation with ex01.go except that both ex01.go and ex02.go belong to the same class of problems - i.e. concurrency), I can't define a variable for waitGroup as

var wg sync.WaitGroup 

I get an error - "variable name is re-declared in this block"

Is there a way to keep the variable names from spilling over to the other files?

like image 785
devak23 Avatar asked Jul 22 '17 11:07

devak23


People also ask

Can global variables be private?

A private global variable in Swift is a global that is only accessible from the file in which it is declared. The book you are using isn't following current best-practice as far as creating singletons in Swift (perhaps it is a little out-dated?).

Why global variables should be private?

The reason is to protect data and members of classes from being changed, inadvertently or on purpose, by other parts of the program. However, you still may need to have variables that can be accessed across your program, and not confined to specific classes.

Can we declare global variable in header file?

The clean, reliable way to declare and define global variables is to use a header file to contain an extern declaration of the variable. The header is included by the one source file that defines the variable and by all the source files that reference the variable.


1 Answers

For the purpose of variable scoping, files have no meaning in Go. Think of all files in a package as if they would be concatenated, which (simplified) is exactly what happens before compilation.

That means: No, there is no way of scoping a variable to a file.

If you need two global WaitGroups, you need to define them as individual variables.

like image 70
Markus W Mahlberg Avatar answered Oct 24 '22 10:10

Markus W Mahlberg