Confusing error message: Not enough arguments in Fooer.Foo

148 views
Skip to first unread message

Brendan Tracey

unread,
Jul 16, 2014, 5:19:33 PM7/16/14
to golan...@googlegroups.com
I understand why this script [0] is wrong, but I don't understand why the error message is what it is. Shouldn't the error message be something like "Cannot perform a method call on an interface type name"?

[0] http://play.golang.org/p/3cfLeym4m5

Jesse McNelis

unread,
Jul 16, 2014, 5:28:13 PM7/16/14
to Brendan Tracey, golang-nuts


On 17 Jul 2014 07:19, "Brendan Tracey" <tracey....@gmail.com> wrote:
>
> I understand why this script [0] is wrong, but I don't understand why the error message is what it is. Shouldn't the error message be something like "Cannot perform a method call on an interface type name"?
>
> [0] http://play.golang.org/p/3cfLeym4m5
>

http://golang.org/ref/spec#Method_expressions

Fooer.Foo is a function that takes a Fooer as it's first parameter.

Frits van Bommel

unread,
Jul 16, 2014, 5:30:00 PM7/16/14
to golan...@googlegroups.com
On Wednesday, July 16, 2014 11:19:33 PM UTC+2, Brendan Tracey wrote:
I understand why this script [0] is wrong, but I don't understand why the error message is what it is. Shouldn't the error message be something like "Cannot perform a method call on an interface type name"?

[0] http://play.golang.org/p/3cfLeym4m5

Fooer.Foo is a method expression, so it's a function that expects a Fooer and two ints as parameters. These are mostly useful for storing as values instead of calling them directly, but calling them directly is perfectly legal as long as you supply the correct parameters.

Shawn Milochik

unread,
Jul 16, 2014, 5:30:37 PM7/16/14
to golan...@googlegroups.com
You don't "instantiate" an interface like it was a subclass of an object.

This works, but almost certainly is not what you want:

What you'd be doing with an interface (if you were using it properly), is to have one or more structs which have a Foo(i, j int) method. Then, you'd have other code that expects to receive a Fooer. Then, you'd pass things (like Bars, in my example) to those functions.

The standard example is the io.Reader interface:

If you have a function that expects to receive an io.Reader (or a *io.Reader), you can pass it an os.File (or *os.File), because it has a Read() method. But you can also pass it other things, including things you invent. That's the purpose of an interface.


Brendan Tracey

unread,
Jul 16, 2014, 5:30:59 PM7/16/14
to Jesse McNelis, golang-nuts
Ah, that makes sense. Thank you.
Reply all
Reply to author
Forward
0 new messages