Tsallaka zuwa abun ciki
Justice Tech School

Methods

A method is a function with a receiver. Use a pointer receiver to modify the value.

Example
package main

import "fmt"

type Rect struct{ W, H int }

func (r Rect) Area() int { return r.W * r.H }
func (r *Rect) Grow()    { r.W *= 2 }

func main() {
	r := Rect{3, 4}
	fmt.Println(r.Area())
	r.Grow()
	fmt.Println(r.Area())
}

Result

12
24

Exercise

Receiver.

func (r ) Grow() {}

Quiz Test

Which receiver can modify the struct?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.