Go-LANG- Slice usage

Hello Team,

Can anyone please elaborate answer to the below question.

package main

import “fmt”

func main() {
arr := [5]int{10, 20, 90, 70, 60}
slice := arr[:3]
fmt.Println(cap(slice))
new_slice := append(slice, 100, 200)
fmt.Println(cap(new_slice))
}

If we consider the elements in Array then the output of the slice would be [10,20,90] now the capacity is 4.

now for the second slice it is [10,20,90,100,200] the capacity would be 6

My output is [4 6]

but the answer to this question is [5 5].

Regards,
Challapuram

Hi @Saikumar-Reddy-Chall ,
I am getting the expected output.

You can make use of the %d & %v format of the fmt.Printf function.
It will give you more wide output to understand this.

Regards,

Hi @Saikumar-Reddy-Chall ,

Basically slices do not own any data on their own. They are just references to existing arrays.
so on the line number 5 which is “slice := arr[:3]” it is printing the capacity of original array which is 5

now on the line number 7 which is “new_slice := append(slice, 100, 200)” creates new array which is using the slice which has the capacity of 5 and overriding the values of the array elements of 4 and 5 to 100 and 200, however we are still going to print the capacity of the “new_slice” which remains the same and it prints the number 5, if you append more elements than it’s capacity it will increase it’s size by doubling the capacity.

Thanks,
Nayan