Error: In stack of struct in go-lang get overwrite? How can we do deep-copy of struct in golang?

huangapple go评论94阅读模式
英文:

Error: In stack of struct in go-lang get overwrite? How can we do deep-copy of struct in golang?

问题

我在Go语言中创建了一个结构体的堆栈。

type Stack struct {
    stack []Vehicle
}

我有这个结构体和方法来创建一个新的结构体实例:

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

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

我正在做的例子:

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

// 将实例推入堆栈
Stack.push(clone(m))

m.Quantity['a'] = 20

Stack.pop(m)

期望的结果:

当我推出堆栈时,我希望得到Quantity['a']的值为10

实际结果:

我得到的值是Quantity['a']20

function clone(vehicle Vehicle*){}

有人可以帮忙吗?在将结构体推入堆栈之前,如何进行深拷贝?或者在克隆方法中应该怎么写才能进行深拷贝?

英文:

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

得分: 1

地图是指向实际地图对象的指针,所以如果你需要进行深拷贝,你必须手动完成:

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

stack.push(m.Copy())
英文:

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())

huangapple
  • 本文由 发表于 2022年9月26日 00:34:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/73846159.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定