# Variable overwrite, Not comprehensible

I do not know how to describe it.

`````` if aa[0].Name != "" {

a.Direktekosten = aa
e = clJahrep(e, a.Direktekosten[0].Summe) //step 1
}

//call

a.Rohgewinn = append(a.Rohgewinn, GXAnsichtenSumme{Summe: e, Name: "Rohgewinn"}) //step 2

log.Println(a.Rohgewinn) //step 3

aa = getXAnsichtInhalt(r, b.Plan_key, "personalkosten")

if aa[0].Name != "" {

a.Personalaufwand = aa
e = clJahrem(e, a.Direktekosten[0].Summe) //Step 4
}
log.Println(a.Rohgewinn) //step 5
``````

Step 1:

i write a struct in e

Step 2:

i set e in a.Rohgewinn

Step 3:

look in a.Rohgewinn and the result is right

Step 4:

Continue to calculate object e

Step 5:

a,Rohgewinn result is change?

Why???

Can you make a reproducible program on play.golang.org?

Step one in troubleshooting somelike this is to reduce the program to the minimum that still exhibits the problem. It is then usually quite straightforward to locate.

The problem is:

Object e becomes in object a.Rohgewinn. If “e” is later calculated, the value in “a.Rohgewinn” is also changed.

What output are you expecting?

I want the “a.Rohgewinn” not changed if I “e” further change. https://play.golang.org/

It’s not.

``````a.Rohgewinn = append(a.Rohgewinn, GXAnsichtenSumme{Summe: e, Name: "Rohgewinn"})
``````

places `e`, a slice, into `a.Rohgewinn`. Here, `e` is copied, but the array backing `e` is not.

Slices are essentially a struct that stores the slice’s length, capacity, and a pointer to an array.

The code you provided copied the struct, but not the array.

1 Like

Okay i understand …

I solved

``````e2 = make([]GXSumme, len(e))
copy(e2, e)
a.Betriebsergebnis = append(a.Betriebsergebnis, GXAnsichtenSumme{Summe: e2, Name: "Betriebsergebnis"})
e2 = nil
``````

thx

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.