Variables can shadow types?

473 views
Skip to first unread message

Kevin Ballard

unread,
Apr 4, 2012, 8:46:54 PM4/4/12
to golang-nuts
I noticed some surprising behavior last night. However, I'm not sure if this is actually a bug, or by design. Basically, it seems that variables can shadow types. This is very odd because Go typically has no trouble distinguishing between types and other tokens, so I don't know why a variable name should be allowed to shadow a type name.


type aStruct struct {
field int
}

func main() {
aStruct := aStruct{1} // this works
aStruct = aStruct{2} // this doesn't
fmt.Println(aStruct)
}

prog.go:11: aStruct is not a type

Was this intentional, or should I file a bug?

-Kevin

-- 
Kevin Ballard

Evan Shaw

unread,
Apr 4, 2012, 8:53:08 PM4/4/12
to Kevin Ballard, golang-nuts
Variables and types live in the same namespace, so one can shadow the
other. Types can also shadow variables:
http://play.golang.org/p/qIIAEI6FpR

It's intentional and works this way because otherwise certain
constructs, like conversions, become ambiguous.

- Evan

Brad Fitzpatrick

unread,
Apr 4, 2012, 8:58:16 PM4/4/12
to Evan Shaw, Kevin Ballard, golang-nuts
And variables can shadow packages:

Paul Samways

unread,
Apr 4, 2012, 9:09:08 PM4/4/12
to Brad Fitzpatrick, Evan Shaw, Kevin Ballard, golang-nuts
Is there actually a way of referencing a type in the package scope after it has been shadowed in the function?

John Asmuth

unread,
Apr 4, 2012, 9:17:57 PM4/4/12
to golan...@googlegroups.com, Brad Fitzpatrick, Evan Shaw, Kevin Ballard
I hope you don't take this as snark, because it's not intended that way, but...

Just don't shadow it.

It's all your code, if you're within the package. You can just change your identifiers around.

si guy

unread,
Apr 5, 2012, 1:12:33 PM4/5/12
to golan...@googlegroups.com
I ran into this when working with the image package. I learned quickly to call my images something other than "image".
Reply all
Reply to author
Forward
0 new messages