본문 바로가기
Go

[Go] Method

by llHoYall 2021. 10. 17.

A Method is a kind of function.

But a method belongs to the receiver. In contrast, function belongs nowhere.

Therefore, a method increases the cohesion of code.

Method Definition

func (RECEIVER) METHOD_NAME() RETURN_TYPE {
  STATEMENTS
}

A receiver can be all local types, and local type is defined as type keyword within the package.

If a receiver exists, it is a method, and if not, it is a function.

package main

import (
  "fmt"
)

type age int

func (a age) add(x int) int {
  return int(a) + x
}

func main() {
  var a age = 10
  b := a.add(5)
  fmt.Println(b)
  // 15
}

This is a simple example of using a receiver and method.

Method with Pointer Receiver

A method can have a pointer-type receiver.

I will make an example for it.

type person struct {
  name string
  age  int
}

func (p person) increaseAge() {
  p.age += 1
}

func main() {
  p := person{"kim", 18}
  p.increaseAge()
  fmt.Println(p) //{kim 18}
}

In the above example, the receiver acts as pass-by-value.

So, the result doesn't remain after the end of the method.

func (p *person) increaseAge() {
  p.age += 1
}

func main() {
  p := person{"kim", 18}
  p.increaseAge()
  fmt.Println(p) //{kim 19}
}

If you change the receiver to a pointer type, the result can remain after the end of the method.

'Go' 카테고리의 다른 글

[Go] Functions  (0) 2021.10.19
[Go] Interface  (0) 2021.10.17
[Go] Slice  (0) 2021.10.16
[Go] Package  (0) 2021.10.16
[Go] Rune and String  (0) 2021.10.16

댓글