P
P
Pretendi2015-11-25 22:00:26
go
Pretendi, 2015-11-25 22:00:26

How to work with slices?

I don't understand how to properly copy slices so that changes to one don't affect the other.

package main

import "fmt"

func Delete(slicePtr *[]int, value int) {
  for i := 0; i < len(*slicePtr); i++ {
    if (*slicePtr)[i] == value {
      if i != 0 {
        *slicePtr = append((*slicePtr)[:i], (*slicePtr)[i+1:len(*slicePtr)]...)
      } else {
        *slicePtr = (*slicePtr)[i+1 : len(*slicePtr)]
        return
      }
    }
  }
}

func main() {
  const Size = 9
  sliceA := make([]int, Size)
  for i := 0; i < Size; i++ {
    sliceA[i] = i + 1
  }
  sliceB := sliceA
  fmt.Println(sliceA, sliceB)
  Delete(&sliceB, 2)
  fmt.Println(sliceA, sliceB)
}

Result:
go run test.go` | done: 1.550204843s ]
[1 2 3 4 5 6 7 8 9] [1 2 3 4 5 6 7 8 9]
[1 3 4 5 6 7 8 9 9] [1 3 4 5 6 7 8 9]

The content of sliceA is a little surprising. The documentation says that changing a slice will affect the slice it was made from, but not the same way! The example shows that the content has changed, but not the length.
More interesting is the issue with structures containing slices. If I create a copy of the structure and start changing the slice inside, this will be reflected in the original. wtf? It turns out that you need to write something like a copy constructor?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikita, 2015-11-25
@Pretendy

https://github.com/golang/go/wiki/SliceTricks
Everything you need is described there)
At the expense of structures... if you need to be able to deep-copy objects, you will have to write something like a copy constructor (c++) , only in Go there is no such thing, you can write the Copy () method, which will return a copy of the object with new pointers, slices and new memory allocated for them. play.golang.org/p/lr9vnTNp-J
UPD: I needed it myself, found https://godoc.org/code.google.com/p/rog-go/exp/deepcopy - a universal implementation of copying.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question