Answer the question
In order to leave comments, you need to log in
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)
}
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]
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question