Limitations on methods, part 2
August 29, 2023
Continuining from yesterday, when we started disecting this section of the spec:
Method declarations
…
A receiver base type cannot be a pointer or interface type and it must be defined in the same package as the method.
Today we’re tackling the second limitation:
A receiver base type cannot be an interface.
At first this might seem a bit counter-intuitive… aren’t interfaces all about methods? Well, yes, but in the other directions. Interfaces are collections of methods. But you can’t define methods on interfaces. To be explicit, this is invalid:
type foo interface {
Foo() error
}
func (f foo) Bar() {} // invalid receiver type foo (pointer or interface type)
If you want to extend the foo
interface with the Bar()
method, the proper way is to extend the foo
type definition:
type foo interface {
Foo() error
Bar()
}
Now it’s up to any types that implement this interface to define a method Bar()
.
Quotes from The Go Programming Language Specification Version of August 2, 2023