Method declaration
- Go course
- Beginner
- Lesson 75/90
- 4 min
Learn to declare methods on structs.
Defining methods
A method is a function bound to a specific type. The receiver is written in parentheses between func and the name:
type Dikdortgen struct{ En, Boy float64 }
func (d Dikdortgen) Alan() float64 {
return d.En * d.Boy
}
r := Dikdortgen{3, 4}
fmt.Println(r.Alan()) // 12The receiver name is usually the type's initial (d); this or self isn't used.
Method or function?
If an operation is directly about a type's data, writing it as a method improves readability: r.Alan() is clearer than Alan(r). Methods are also how interfaces are satisfied (you'll see later). Method values can be passed around like functions too: f := r.Alan; f().
Practice Area and perimeter
Write the Alan() and Cevre() methods for Dikdortgen (En, Boy float64). Print both for Dikdortgen{3, 4} on one line.
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
type Dikdortgen struct{ En, Boy float64 }
func (d Dikdortgen) Alan() float64 { return d.En * d.Boy }
func (d Dikdortgen) Cevre() float64 { return 2 * (d.En + d.Boy) }
func main() {
r := Dikdortgen{3, 4}
fmt.Println(r.Alan(), r.Cevre())
}Expected output
12 14
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which types can have methods added?
- Only interfaces
- Any type defined in the same package Correct answer
- Only structs
- Built-in types like int directly too
Explanation: You can add methods to any type you define, like type Puan int; you can't add them directly to another package's type (e.g. int, time.Time).
2 Receiver
func (____ Dikdortgen) Cevre() float64 {
return 2 * (d.En + d.Boy)
}
func (d Dikdortgen) Cevre() float64 {
return 2 * (d.En + d.Boy)
}
Explanation: The receiver name is the variable used in the body; here, d.
3 Part
| Term | Meaning |
|---|---|
(d Dikdortgen) |
Receiver |
Alan |
Method name |
r.Alan() |
Method call |
f := r.Alan |
Method value |