tour icon indicating copy to clipboard operation
tour copied to clipboard

tour: panic out of nowhere

Open piapip opened this issue 6 years ago • 4 comments

Context: https://tour.golang.org/moretypes/7

s[3] = 4 cause panic. Maybe slice isn't dynamically-sized anymore.

piapip avatar Oct 14 '19 06:10 piapip

The slice is created with length 3 (index 0,1 and 2). so accessing index 3 gives error. The capacity is still 5. You may extend the slice first and then access index 3. Notice that the address is same after adding an element indicating it is the same slice that is extended

package main

import "fmt"

func main() {
	primes := [6]int{2, 3, 5, 7, 11, 13}

	var s []int = primes[1:4]
	fmt.Printf("len=%d cap=%d %v add=%p \n", len(s), cap(s), s ,s)
	s= append(s,4)
	fmt.Printf("len=%d cap=%d %v add=%p \n", len(s), cap(s), s ,s)

}

Output: len=3 cap=5 [3 5 7] add=0x456004 len=4 cap=5 [3 5 7 4] add=0x456004

devendramu avatar Oct 20 '19 06:10 devendramu

oh so if the slice has reached its cap, we can't append more value into the slice huh... Since the slice is created so we don't need to predetermine the size of the array, should I just initialize the slice with the cap of 9999 ?

piapip avatar Oct 21 '19 02:10 piapip

If slice reaches the capacity, you can still append element. Once capacity is reached, Internally append create a new bigger size array and slice starts referencing to new one

devendramu avatar Oct 21 '19 04:10 devendramu

You can append to a slice at any time, but s[3] on a length 3 slice is not trying to append, it is saying "given a slice without an index 3, please put something at index 3", which correctly does not work.

"Appending to a slice" is later in the tour: https://go.dev/tour/moretypes/15

crisman avatar Mar 09 '23 23:03 crisman