Back to questions
JuniorTheoryCommon
What does the program print?
package main
import "fmt"
type Rect struct{ W, H int }
func (r Rect) Area() int { return r.W * r.H }
func Area(w, h int) int { return w + h }
func main() {
r := Rect{2, 3}
fmt.Println(r.Area(), Area(2, 3))
}6 5
- Expecting a compile error: a method's name belongs to its type, so the method
Rect.Areaand the functionAreado not clash. - Expecting both calls to reach one function:
r.Area()calls the method withras its receiver, andArea(2, 3)the plain function.
- Why must a method's receiver type be defined in the same package?
- How does the receiver let you call a method as
c.Inc()instead ofInc(c)?