Sobes.tech
Senior

What is the difference between a function and a method in Go? What is the technical difference in terms of memory handling?

sobes.tech AI

Answer from AI

In Go, a function is an independent block of code that is called by name and can accept parameters and return values. A method is a function associated with a specific type (receiver), which is called through an instance of that type.

Technically, a method is a function with an additional implicit parameter — the receiver, which can be a value or a pointer. This affects memory management:

  • If the receiver is a value, the method gets a copy of the object, and changes inside the method do not affect the original.
  • If the receiver is a pointer, the method works with the original object, and changes are reflected on it.

Example:

package main
import "fmt"

type Counter struct {
    count int
}

// Method with receiver by value
func (c Counter) IncrementValue() {
    c.count++
}

// Method with receiver by pointer
func (c *Counter) IncrementPointer() {
    c.count++
}

func main() {
    c := Counter{count: 0}
    c.IncrementValue()
    fmt.Println(c.count) // 0, because it's a copy
    c.IncrementPointer()
    fmt.Println(c.count) // 1, because the original is modified
}

Thus, a method is a function with an additional receiver parameter, which affects data passing and memory management.