0
0
GoHow-ToBeginner · 3 min read

How to Create 2D Slice in Go: Syntax and Examples

In Go, you create a 2D slice as a slice of slices using [][]Type. You can initialize it with nested literals or make it dynamically with make for rows and columns.
📐

Syntax

A 2D slice in Go is declared as [][]Type, which means a slice of slices of a specific type. You can create it using literals or the make function.

  • Declaration: var matrix [][]int declares a 2D slice of integers.
  • Literal initialization: matrix := [][]int{{1,2}, {3,4}} creates a 2D slice with two rows.
  • Dynamic creation: Use make([][]int, rows) to create the outer slice, then initialize each inner slice.
go
var matrix [][]int

// Literal initialization
matrix = [][]int{{1, 2}, {3, 4}}

// Dynamic creation
rows := 3
cols := 4
matrix = make([][]int, rows)
for i := range matrix {
    matrix[i] = make([]int, cols)
}
💻

Example

This example shows how to create a 3x3 2D slice, fill it with values, and print it row by row.

go
package main

import "fmt"

func main() {
    rows, cols := 3, 3
    matrix := make([][]int, rows)
    for i := range matrix {
        matrix[i] = make([]int, cols)
        for j := range matrix[i] {
            matrix[i][j] = i*cols + j + 1
        }
    }

    for _, row := range matrix {
        fmt.Println(row)
    }
}
Output
[1 2 3] [4 5 6] [7 8 9]
⚠️

Common Pitfalls

One common mistake is to create only the outer slice and forget to initialize the inner slices, which causes a runtime panic when accessing inner elements.

Another is assuming all inner slices have the same length; in Go, inner slices can have different lengths (ragged slices).

go
package main

import "fmt"

func main() {
    // Wrong: inner slices not initialized
    matrix := make([][]int, 2)
    // matrix[0][0] = 1 // This will panic: index out of range

    // Correct: initialize inner slices
    for i := range matrix {
        matrix[i] = make([]int, 2)
    }
    matrix[0][0] = 1
    fmt.Println(matrix)
}
Output
[[1 0] [0 0]]
📊

Quick Reference

  • Declare 2D slice: var s [][]int
  • Initialize with literals: s := [][]int{{1,2},{3,4}}
  • Create dynamic 2D slice: Use make([][]int, rows) and initialize each inner slice
  • Access element: s[row][col]
  • Lengths: len(s) for rows, len(s[0]) for columns (if inner slice exists)

Key Takeaways

A 2D slice in Go is a slice of slices declared as [][]Type.
Initialize both outer and inner slices to avoid runtime errors.
Inner slices can have different lengths, allowing ragged arrays.
Use make to create slices dynamically and fill them with values.
Access elements with s[row][col] syntax.