-2

I have written a simple stack implementation. This works as expected.

package main

import "fmt"

type Stack struct {
    data []interface{}
}

func (s *Stack) isEmpty() bool {
    return len(s.data) == 0
}

func (s *Stack) push(item interface{}) {
    s.data = append(s.data, item)
    //fmt.Println(s.data, item)
}

func (s *Stack) pop() interface{} {
    if len(s.data) == 0 {
        return nil
    }
    index := len(s.data) - 1
    res := s.data[index]
    s.data = s.data[:index]
    return res
}

func main() {
    var stack Stack

    stack.push("this")
    stack.push("is")
    stack.push("sparta!!")

    for len(stack.data) > 0 {
        x := stack.pop()
        fmt.Println(x)
    }
}

However, if I changed the three methods from receiver by pointer to receiver by value as below. Then the main does not print anything. It seems that every time I called push method, the stack is reinitialized. Why is that?

func (s Stack) isEmpty() bool {
func (s Stack) push(item interface{}) {
func (s Stack) pop() interface{} {
drdot
  • 3,215
  • 9
  • 46
  • 81

1 Answers1

1

In value receiver Go makes a copy of the variable and makes changes to the copy. Only in reference receiver the actual stack variable gets updated.

For more details, https://tour.golang.org/methods/4

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Surya
  • 2,429
  • 1
  • 21
  • 42