in golang what does the [:] syntax differ from the array assignment?

Viewed 1986

I am currently going through the GoLang tutorials and have the following doubt.

arr1:=[...]int{1,2,3}
arr2:=arr1
arr1[1]=99
fmt.Println(arr1)
fmt.Println(arr2)

it outputs the following statements

[1 99 3]
[1 2 3]

here only array a is modified, which makes sense as an array is treated as values.

if I try following things get confusing

a:=[...]int{1,2,3}
b:=a[:]
a[1]=88
fmt.Println(a)
fmt.Println(b)

this results in printing

[1 88 3]
[1 88 3]

Question: does this mean saying b:=a creates a copy of the array and saying b:=a[:] will create a slice that will point to the underlying array ('a' in this case)?

1 Answers

Slicing does not copy the slice's data. It creates a new slice value that points to the original array. This makes slice operations as efficient as manipulating array indices. Therefore, modifying the elements (not the slice itself) of a re-slice modifies the elements of the original slice

https://blog.golang.org/slices-intro

Check above link for internal structure behind Slice

Related