arr := [5]int{10, 20, 90, 70, 60}
slice := arr[:3]
fmt.Println(cap(slice)) //5
slice_2 := make([]int, 10, 10)
fmt.Println(slice_2)
new_slice := append(slice, slice_2...) //[10 20 90 0 0 0 0 0]
fmt.Println(new_slice)
fmt.Println(cap(new_slice))
Why cap is 14 ? as per lecture, capacity should get doubled if underlying array is smaller i.e. 5*2=10
fmt.Println(cap(new_slice))
There is quite a complicated algorithm behind slice reallocation once you exceed capacity. Contrary to what the course video says, it doesn’t always double the capacity when the slice needs to be grown.
Hi @sharmamitul72
I have now produced a detailed write-up on how slices work.
# Bonus: How do slices *really* work?
Now that you have reached the end of the course and learned about arrays, slices, structs and pointers, we can take a deep dive into the mechanics of what makes a slice work under the hood. Hopefully this covers all the questions raised on the KodeKloud forums about slices.
In some of the code examples below, it is stated "pseudo-code". For those that haven't come across this term, pseudo-code shows a description of the logic that would happen in the *real* code, some of which in these cases would have been written in assembly language rather than pure Go in the Go runtime, for speed."pseudo-function" indicates a made up function call representative of what is actually happening under the hood. Don't try running any of the pseudo-code, it won't work! It serves only as an illustration. Any example complete with `package` and `import` will run.
* [Refresher](#refresher)
* [Slice Representation](#slice-representation)
* [Slicing arrays and other slices](#slicing-arrays-and-other-slices)
* [Growing Slices](#growing-slices)
## Refresher
You've learned that an array is passed by value. This means that if you pass an array as a function argument, changing the array from inside the function has no effect on the caller's array, since the function gets a complete copy of the *entire* array...
```go
package main
import "fmt"
This file has been truncated. show original