CodeBlanks Logo Icon CodeBlanks

Summary - Methods

Combine value and pointer receivers to write a bank account.

Methods summary

A method = a function with a receiver: func (t T) Name(). A value receiver works on a copy and is for read-only work; a pointer receiver changes the original and is for large types or types that must not be copied. Methods of embedded types are promoted and can be shadowed; methods that return the receiver can be chained. A String() string method sets fmt's print format.

Method values and expressions

Methods can also be used as functions:

h := &Hesap{}
yatir := h.Yatir        // method value: bound to h
yatir(50)
f := (*Hesap).Yatir     // method expression: receiver is the first parameter
f(h, 25)
fmt.Println(h.Bakiye)   // 75

Method values are handy when starting goroutines and passing callbacks: go h.Calis().

Practice Point type

For type Nokta struct{ X, Y int }, write a value-receiver String() (format "(X, Y)") and a pointer-receiver Tasi(dx, dy int). After n := Nokta{1, 2} and n.Tasi(3, 4), print fmt.Println(n).

Starter code

main.go
package main

import "fmt"

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import "fmt"

type Nokta struct{ X, Y int }

func (n Nokta) String() string { return fmt.Sprintf("(%d, %d)", n.X, n.Y) }

func (n *Nokta) Tasi(dx, dy int) {
    n.X += dx
    n.Y += dy
}

func main() {
    n := Nokta{1, 2}
    n.Tasi(3, 4)
    fmt.Println(n)
}

Expected output

(4, 6)

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which is true of a type's method set?

  • *T has both T- and *T-receiver methods; T only T-receiver ones Correct answer
  • They are the same
  • T contains everything
  • *T has only *T-receiver methods

Explanation: This rule matters for interface satisfaction: an interface implemented with pointer-receiver methods is satisfied only by *T.

2 Print format

Question
func (n Nokta) ____() string {
    return fmt.Sprintf("(%d, %d)", n.X, n.Y)
}
Answer
func (n Nokta) String() string {
    return fmt.Sprintf("(%d, %d)", n.X, n.Y)
}

Explanation: fmt prints types that have a String() string method in their own format.

3 Group summary

Term Meaning
(t T) Value receiver
(t *T) Pointer receiver
Promotion Embedded methods
return s Chaining

All lessons in Beginner