A
A
Alexey2018-07-04 10:24:21
go
Alexey, 2018-07-04 10:24:21

Why does Go overwrite the elements of an array when I modify a copy of that array?

There is a code where I work with the structure.
For a specific job, I need to select the desired structure by key - work with it, change array elements, execute queries. And so I can call this structure several times.
But after the first processing of the structure, changing the elements of the array in a copy of the structure, the value of the elements of the array (slice) in the global Map also changes.
How to fix this? Or how to get rid of this behavior and ensure that the values ​​in the global Map do not change, but only change in the temporary structure for work?
Here is the code

package main

import "fmt"

type typeElMap struct {
  Name string
  Data []string
}

var MainData map[string]typeElMap


func main(){

  MainData = make(map[string]typeElMap,0)

  MainData["key"] = typeElMap{Name:"Digit", Data: []string{"1","2","3"}}

  tmp := MainData["key"]

  // WORK
  tmp.Name = "NEW NAME"
  tmp.Data[0] = "A"
  // END WORK

  fmt.Println(MainData["key"]) // Результат {Digit [A 2 3]} - имя НЕ поменялось, а массив изменился




  a:= []int{1,2,3}
  b := a
  b[0] = 777
  fmt.Println(a) // Тоже результат [777 2 3]

}

Answer the question

In order to leave comments, you need to log in

4 answer(s)
L
longclaps, 2018-07-04
@longclaps

Use deep copy .

A
Alexander Pavlyuk, 2018-07-04
@pav5000

This behavior is because a slice is just a structure with 3 fields:
1. A pointer to the beginning of the data.
2. The number of elements that are already used in the slice
3. The total number of elements in the allocated memory block (the slice can grow up to this threshold without memory allocation)
That is, there is essentially no data in the slice, it simply points to the data. By copying a slice variable, you are copying a pointer.
Read more here
As it was rightly said above, you need a deep copy

G
GavriKos, 2014-10-30
@worlxxaker

Most likely somewhere in /data/data/appname/cache. You can't get it without root.

O
oia, 2014-10-30
@oia

look in the vk folder, or connect the phone to the pc and look at the folders nafig such questions here post business for 2 minutes

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question