Catching shadowed built-in types

Viewed 95

In go it is possible to shadow bult-in types like int; so is legal this:

var a int
a = 1
fmt.Println(a)

int := 2  //<-- catching this
fmt.Println(int)

Playground: https://play.golang.org/p/lU6Z8BW7hzS

Is it possible to catch it with some tools?

2 Answers

Not sure if this helps, but the syntax highlighter for the editor I use (Vim) detects predefined types [1], including int:

syn keyword     goSignedInts        int int8 int16 int32 int64 rune

So it doesn't warn you of the situation you describe, but the identifier will be a bold green instead of a normal black, so it's pretty noticeable.

  1. https://github.com/vim/vim/blob/1ad72c8e/runtime/syntax/go.vim#L70

There is proposal for that: https://github.com/golang/go/issues/38832

Not just shadow is legal, but also struct field:

    type myStruct struct {
        int
    }
    a := myStruct{}
    a.int = 2

GoLand has IDE check, it will show warning: "Variable 'int' collides with the builtin type", but it show no warning for struct fields.

The problem is: the language allows it, so a few programmers may use this feature on purpose.

Related