Declare methods and receivers
Declare methods and receivers
A method is a function associated with a defined receiver type. The receiver appears before the method name: func (r Rectangle) Area() int. Call it with r.Area(). Unlike an ordinary function, a method is selected through its receiver. The receiver type must be defined in the same package and cannot itself be a pointer or interface type.
package main
import ( "fmt")
type Rectangle struct{ W, H int }
func (r Rectangle) Area() int { return r.W * r.H }func main() { r := Rectangle{W: 4, H: 3} fmt.Println(r.Area())}The receiver r is a parameter containing a copy of the rectangle. The method reads its fields and returns the product. Methods are declared at package scope, not inside a struct declaration.
Expected output:
12Methods on non-struct types
package main
import ( "fmt")
type Minutes int
func (m Minutes) Seconds() int { return int(m) * 60 }func main() { fmt.Println(Minutes(3).Seconds())}Minutes is a local defined integer type, so it can have methods too. You cannot attach a new method directly to int or to a type defined in another package. Define a local type when you need custom behavior.
Expected output:
180Try it locally
Define Square with Side int and an Area method. Print the area for side 5.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Methods 01: Declare methods and receivers
Check the lesson objective before moving on.
Where does the receiver appear in a method declaration?
Which type can have a newly declared method in the same package?