Runtime error: index out of range

https://play.golang.org/p/wJtNmkiuD1

My code is over here
I want to be output : Hello Its me
How can i do

var b is nil until you allocate some space for it. Allocate at least three sub-slices and make the third one have two entries, then you can access b[2][1] without getting a panic.

https://play.golang.org/p/qf2YvYjdPq

1 Like

Hey @favorman,

Like @christophberger has stated, you have to allocate before you try to add to a slice like that.

For larger slices, or even in general, here is how I would probably pre-allocate a 2 dimensional slice like you’re using if you know what sizes you want the rows and cols to be.

package main

import "fmt"

func main() {
	// 2d slice row and column sizes.
	rows, cols := 3, 2

	// Make a slice of slices of size rows.
	b := make([][]string, rows)

	// Make each of the 2d slice's columns to size cols.
	for i := range b {
		b[i] = make([]string, cols)
	}

	a := " Me"
	b[2][1] = "Hello Its"
	b[2][1] += a

	// Print b[2][1]
	fmt.Println(b[2][1])
}

Edit: You can also just use a 2d array, but that depends if you want to be using an array of arrays or a slice of slices, but like this example, you really don’t have to do much initialization for a 2d array:

package main

import "fmt"

func main() {
	// Make a 2d array.
	var b [3][2]string

	a := " Me"
	b[2][1] = "Hello Its"
	b[2][1] += a

	// Print b[2][1]
	fmt.Println(b[2][1])
}

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.