shadowing of types by variables

182 views
Skip to first unread message

Gorka Guardiola

unread,
Jan 13, 2023, 5:22:46 AM1/13/23
to golang-nuts
These programs compile and work according to my reading of the spec, but I found them surprising.


According to the spec it seems like it is legal to shadow a type with a variable, even a builtin type.
Is there any specific rationale for this? I guess that it makes scoping checks easier and faster, but still.

More "interesting" programs in the same vein:

--
- curiosity sKilled the cat

Brian Candler

unread,
Jan 13, 2023, 7:12:07 AM1/13/23
to golang-nuts
The rationale, I understand, is that it helps with the Go compatibility promise: when new types / constants / functions are added to the language, they don't break existing code.

wagner riffel

unread,
Jan 16, 2023, 8:46:31 PM1/16/23
to Gorka Guardiola, golang-nuts
On 1/13/23 07:20, Gorka Guardiola wrote:
> According to the spec it seems like it is legal to shadow a type with a
> variable, even a builtin type.
> Is there any specific rationale for this? I guess that it makes scoping
> checks easier and faster, but still.
>

I don't think there is any special rationale behind it, in Go builtin
types are predefined identifiers, not keywords as usual in other
languages, thus those follow rules of identifiers, not keywords.
Although it feels astonishing that you can shadow even predefined
constants like "true := false", in my experience this haven't shown to
be an issue.

-w

Ian Lance Taylor

unread,
Jan 16, 2023, 10:04:15 PM1/16/23
to wagner riffel, Gorka Guardiola, golang-nuts
There is a rationale: we can add new predeclared identifiers without
breaking existing working code.

For example, the Go 1.18 release added two new predeclared
identifiers: `any` and `comparable`. Because they were predeclared
identifiers, not keywords, existing code that used them as variable
names continued to work.

Ian

Gorka Guardiola

unread,
Jan 17, 2023, 1:45:17 AM1/17/23
to Ian Lance Taylor, wagner riffel, golang-nuts
Yes, I understood the idea from Brian's explanation. Makes adding new predeclared names (types, literals...) a compatible change.

Thanks.
Reply all
Reply to author
Forward
0 new messages