Clarification on using variables from packages

205 views
Skip to first unread message

Brendan Tracey

unread,
May 3, 2013, 3:05:19 PM5/3/13
to golan...@googlegroups.com
I'd just like to confirm that I understand.

One can modify the value of a variable in another package
I assume that this is a "global" change, in that all other places that there is a pointer to that variable are affected, just like normal pointers. Similarly, just like normal pointers, if you want to make sure that your variable is sandboxed, you should make a copy of the package variable, and take a reference of the copy, rather than making a reference to the package variable directly. Lastly, for this reason, it's in general a bad idea to have a "Default variable" in a package which is a pointer to a struct (even if the variable is large), because it makes it difficult to make multiple copies of that struct. Instead, a non-pointer value should be supplied, to let the user make a copy and then take a reference themselves (or a NewDefault() should be written). 

Thanks in advance.

Andrew Gerrand

unread,
May 3, 2013, 3:07:32 PM5/3/13
to Brendan Tracey, golang-nuts
On 3 May 2013 15:05, Brendan Tracey <tracey....@gmail.com> wrote:
I'd just like to confirm that I understand.

One can modify the value of a variable in another package
I assume that this is a "global" change

Yes.
 
, in that all other places that there is a pointer to that variable are affected, just like normal pointers. Similarly, just like normal pointers, if you want to make sure that your variable is sandboxed, you should make a copy of the package variable, and take a reference of the copy, rather than making a reference to the package variable directly.

Yes.
 
Lastly, for this reason, it's in general a bad idea to have a "Default variable" in a package which is a pointer to a struct (even if the variable is large), because it makes it difficult to make multiple copies of that struct. Instead, a non-pointer value should be supplied, to let the user make a copy and then take a reference themselves (or a NewDefault() should be written). 

Not really. It's generally understood that package-global variables should be modified with care.

Andrew

Brendan Tracey

unread,
May 5, 2013, 11:55:57 PM5/5/13
to golan...@googlegroups.com, Brendan Tracey
I understand, thanks for the reply
Reply all
Reply to author
Forward
0 new messages