In the following Go program, I am creating mySlice1
with 6 elements in it. mySlice2
is initialized with 3 elements.
From mySlice1
I am taking 1st two elements into mySlice2
. Also using copy
function of slice, 3 elements of mySlice1
are overwritten to mySlice2
.
package main
import "fmt"
func main() {
mySlice1 := []int{1, 3, 5, 7, 9, 11}
mySlice2 := make([]int,3)
mySlice2 = mySlice1[0:2]
copy(mySlice2,mySlice1)
fmt.Printf("%T\t%T
", mySlice1,mySlice2)
fmt.Println(mySlice1,mySlice2)
}
But while printing mySlice2
I am getting two elements only.
$ go run main.go
[]int []int
[1 3 5 7 9 11] [1 3]
Why is mySlice2
not getting overwritten while using copy
function?
You are reinitializing mySlice2 variable at this point:mySlice2 = mySlice1[0:2]
.
So, the previous reference to the slice with 3 elements is gone.
To remedy this, simply remove this sentence and re-run the program.
If you want mySlice2
to have 3 elements, you should use:
myslice2 = mySlice1[0,3]
Or just:
copy(mySlice2,mySlice1)
You did create a slice with length 3, but the you then reassign it to a length of 2. You can see it using len(mySlice2)
before and after the assignments
Your code is working as expected.
You are copying the first three values from the mySlice1
into mySlice2
, hence you are actually copy the memory addresses pointing to the first three items from mySlice1
slice.
When you are declaring the mySlice2
actually you are initializing the slice index values with zero's (this is how Go slices are working). Then you copy the first three values from slice1 into slice2. This does not means that mySlice2
values are changed. If you change mySlice2
0th index to let's say 1 the mySlice1
first value is changed accordingly, because as i mentioned the indexes are referenced by their memory addresses.
package main
import "fmt"
func main() {
mySlice1 := []int{0, 3, 5, 7, 9, 11}
mySlice2 := make([]int,3)
mySlice2 = mySlice1[0:2]
mySlice2[0] = 1
copy(mySlice2,mySlice1)
fmt.Printf("%T\t%T
", mySlice1,mySlice2)
fmt.Println(mySlice1,mySlice2)
// Output
// [1 3 5 7 9 11] [1 3]
}