Uniqueness of methods
September 5, 2023
Oops! Yesterday I live-streamed… to the wrong link! If you followed the link I shared yesterday, you were probably confused. But the good news is, you can still catch the replay.
Method declarations
…
For a base type, the non-blank names of methods bound to it must be unique. If the base type is a struct type, the non-blank method and field names must be distinct.
These uniqueness rules are quite predictible! But let’s go over it to be complete, anyway.
type X int
func (X) Foo() {}
func (x *X) Foo() {} // Invalid; Foo is already defined as a method on this type
Or in the case of a struct:
type Person struct {
Name string
}
func (p *Person) Name() string { // Invalid. Name cannot be a field and a method
return p.Name
}
The spec continues with an example, which we’ll get out of the way today so that tomorrow we can talk about generics as they relate to methods.
Given defined type
Point
the declarationsfunc (p *Point) Length() float64 { return math.Sqrt(p.x * p.x + p.y * p.y) } func (p *Point) Scale(factor float64) { p.x *= factor p.y *= factor }
bind the methods
Length
andScale
, with receiver type*Point
, to the base typePoint
.
Quotes from The Go Programming Language Specification Version of August 2, 2023