Go compiler not consistent with function overloading errors

I’m learning Go and was checking if Go supports function overloading. Go does not support function overloading, which is fine. But, the compiler generates inconsistent error messages for function overloading.

If you overload a function, the compiler will rightly identify the previous declaration. But, in the function invocations, it complains on the invocations of the first declaration and not the last.

One would expect it to complain on the redeclaration and invocations of the redeclarations.

./prog.go:11:6: f redeclared in this block
prog.go:7:6: previous declaration
./prog.go:16:6: f redeclared in this block
prog.go:11:10: previous declaration
./prog.go:23:3: not enough arguments in call to f
have ()
want (int, int)
./prog.go:24:3: not enough arguments in call to f
have (number)
want (int, int)

Go build failed.

Here’s another example with variable redeclarations instead of function redeclarations.

It’s interesting, but I don’t think it’s a bug. As soon as you redeclared the function, anything after that just compounds on that initial issue. It’s like a syntax error: If you miss a curly brace in a function, you’ll get an error. You might then get errors elsewhere in the files about other functions, constants, variables, etc. not existing, even when they do exist; it’s just that the missing curly brace broke the namespace.

Because the Go language doesn’t support overloading, it probably has some code somewhere to report when names are redeclared, but nothing else. Perhaps it looks something like this:

for _, obj := range compiledPkgObjects {
    if old, ok := pkgNamespace[obj.Name]; ok {
        log.Logf("redeclaration of %s ...", obj.Name)
    }
    pkgNamespace[obj.Name] = obj
}

So first, f() is defined, then f(int) overwrites it, then f(int, int) overwrites that. When main's names are being resolved, it looks up f and sees f(int, int).

1 Like

Thanks Sean for the explanation. It probably is not a bug.

Usually, compilers don’t update the symbol table, if they error on any symbol. So, I thought it was strange.

The language specification is not very clear on this. It essentially says multiple declarations are not allowed, but it doesn’t explicitly say, redeclarations are not allowed.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.