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?
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?).
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.
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.
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 WaitGroup
s, you need to define them as individual variables.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With