-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{} {
mh-cbon
  • 6,683
  • 2
  • 27
  • 51
drdot
  • 2,861
  • 9
  • 40
  • 72

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

Flimzy
  • 68,325
  • 15
  • 126
  • 165
Luna Lovegood
  • 1,922
  • 14
  • 30