Looking for explanation go code

Could someone explain me, why cap is 1536 ?

As what delivered in Go lecture for append function: if the underlying array is small then bigger array
New slice returned will have 2 times the initial capacity, if initial capacity do not have capacity.
so, it should be double of 1025 i.e. 2050 ??

c := make([]int, 1025, 1025)
c = append(c, 1)
fmt.Println(len(c), cap(c))

output len(c) =1026 , cap(c) = 1536


I’ll answer this and your other question about slices here. I’ll warn you, the answer isn’t straight forward!

Slice management (allocation, deallocation, resizing, copying) etc. is done by the built-in libraries that are associated with the version of Go you’re using. When the courses were created, they were almost certainly done on a version several before the current (1.20).

As the creators of Go try to make it better/faster etc, they change the internal implementations of these built-in functions, thus what you’re seeing is probably a recent optimization to how they handle capacity when a slice is resized. It makes more efficient use of memory to round allocations to a number divisible by the word size of the CPU (64 bit, i.e. 64), which 1536 is.

Once the slices are getting quite big, it makes no sense to allocate double the size to add one more element, or you’ll soon start running out of memory.

The source for slice reallocation is here, but it’s very complicated. Suffice to say, sometimes the new capacity will be double the old capacity, however there are several factors in the algorithm that may make it be something else.


Can you tell me an answer when such question being asked in interview ? answer should be it depends or some better explanation ? because, i couldn’t understood this line
t makes more efficient use of memory to round allocations to a number divisible by the word size of the CPU (64 bit, i.e. 64), which 1536 is

As a developer, and especially in a language such as Go where you are much closer to how memory is allocated (due to the use of pointers) than you are in languages like Python, it is worth understanding a bit about how computers work internally.

When a CPU makes a request for the content of some memory, then it is more efficient if those blocks of memory are sized at a ratio compatible with the CPU’s word size (how many bits it is).

You should be aware that 8 bits is one byte and 64 bits is therefore 8 bytes. If the capacity of a memory allocation is divisible by 8, then that’s nice and efficient for the CPU’s memory controller. If the block is divisible by a larger power of 8 (like 64), it’s more efficient still, as RAM is arranged in arrays of a size larger than 8 (depends on the RAM).

You’re unlikely to be asked stuff like this in a junior interview, but you should be aware of it.