-2

I have created a stack of struct in Go.

type Stack struct {
    stack []Vehicle
}

I have this struct and method to create a new struct instance:-

type Vehicle struct {
Name string
Quantity map[string]interface{}
}

function NewVehicle(name string) *Vehicle {
v := &Vehicle{Name:name}
v.Quantity = make(map[string]interface{})
return v
}

What I am doing for example:-

m := NewVehicle("Two Wheeler")
m.Quantity['a'] = 10

// pushing stack 
Stack.push(clone(m))

m.Quantity['a'] = 20

Stack.pop(m)

Expected:-

As I pushed instance with Quantity['a'] = 10 when I pop the stack then it should give me value 10 of Quantity['a']

Actual:-

I am getting the value 20 of Quantity['a']

function clone(vehicle Vehicle*){}

Can anybody help in this, how deep copy of the struct before pushing in the stack? or what will be in the clone method to deep copy the struct?

1 Answers1

1

Map is a pointer to the actual map object, so if you need to deep-copy it, you have to do it manually:

func (v Vehicle) Copy() *Vehicle {
   ret:=NewVehicle(v.Name)
   for k,v:=range v.Quantity {
       ret[k]=v
   }
   return ret
}
...

stack.push(m.Copy())
Burak Serdar
  • 46,455
  • 3
  • 40
  • 59