go / beginner
Snippet
Methods on Types
A method is a function with a special receiver argument. It allows you to attach behavior to structs.
snippet.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package mainimport "fmt"type Rectangle struct {Width, Height int}func (r Rectangle) Area() int {return r.Width * r.Height}func main() {rect := Rectangle{Width: 10, Height: 5}fmt.Println("Area:", rect.Area())}
Breakdown
1
func (r Rectangle) Area() int {
Defines a method named Area that belongs to the Rectangle struct.
2
(r Rectangle)
The receiver parameter, making this function a method of Rectangle.
3
rect.Area()
Calls the method on a specific instance of the Rectangle.