Is it possible to define global variable in Go?

378 views
Skip to first unread message

Lambda

unread,
Apr 15, 2010, 4:56:13 AM4/15/10
to golang-nuts
My situation is:
package a call a function in package b
package b use a const defined in package a

When I compile, it says 'recursive call during initialization'
The possible reason is what I said above.

Now my question is, may I use a global variable?
I know using global variables is not a good practice, then is there
alternative ways?
How to improve the design of the code?

roger peppe

unread,
Apr 15, 2010, 4:59:39 AM4/15/10
to Lambda, golang-nuts

mutually referring packages aren't allowed in Go.

your best bet is either to merge the packages or
shuffle things so there's no mutual reference (e.g. move
the const definition into package b)

Xiance SI(司宪策)

unread,
Apr 15, 2010, 5:04:30 AM4/15/10
to Lambda, golang-nuts
What about creating a package c that holds all constants for both a and b to use?



--
To unsubscribe, reply using "remove me" as the subject.

Jessta

unread,
Apr 15, 2010, 5:10:24 AM4/15/10
to Lambda, golang-nuts
On Thu, Apr 15, 2010 at 6:56 PM, Lambda <steph...@gmail.com> wrote:
> My situation is:
> package a call a function in package b
> package b use a const defined in package a
>
> When I compile, it says 'recursive call during initialization'
> The possible reason is what I said above.

This sounds like you have a design problem. If package a and package b
are so interlinked you should just make them the same package(you can
spread a package over multiple files).
posting a link to your code might help as help you with the design issues.

- jessta
--
=====================
http://jessta.id.au

Charles Hixson

unread,
Apr 15, 2010, 6:16:16 PM4/15/10
to golang-nuts
I don't actually think it's a design problem, per se. Just a design
problem in the context of go. But the prior suggestion of "create a
module c to hold the parts shared by a and b" sounds reasonable as a
solution in the context of go.

The solution of making packages so large that they include everything
they might need access to doesn't appeal to me, even if you ARE allowed
to divide a package among multiple files.
I also feel that go has a weakness in the control of variable
visibility, but I'm not sure about this yet.

Global variables are certainly to be avoided. Even if one really DOES
need something to be global, one should always consider breaking it out
into a package that can be included where needed.

Reply all
Reply to author
Forward
0 new messages