Golang : 2 dimensional array example
An example of how to create 2 dimensional array in Golang. Since arrays are fixed size construct, we must specify the dimension first before allocating memory for the array and only then we are able to manipulate the array.
Here we go!
package main
import (
"fmt"
"runtime/debug"
)
func main() {
var rows, columns int
fmt.Println("Creating a 2 dimensional array of integer type ")
fmt.Print("Enter number of rows : ")
fmt.Scan(&rows)
fmt.Print("Enter number of columns : ")
fmt.Scan(&columns)
// allocate memory for 2 dimension array of integer type with
// [][]int
// and use number of rows to determine the size
array := make([][]int, rows)
// followed by columns
for i := range array {
array[i] = make([]int, columns)
}
array[0][0] = 0 // in progamming world, starting counting from zero
array[rows-1][columns-1] = rows * columns // assign value
// print all assigned values by rows
for r := range array {
fmt.Printf("row(%d) - %d\n", r, array[r])
}
// trigger manual garbage collection to reclaim allocated memory
array = nil
debug.FreeOSMemory()
}
Sample output :
Creating a 2 dimensional array of integer type
Enter number of rows : 4
Enter number of columns : 2
row(0) - [0 0]
row(1) - [0 0]
row(2) - [0 0]
row(3) - [0 8]
See also : Golang : How to iterate over a []string(array)
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+3.9k Unix/Linux : How to pipe/save output of a command to file?
+8.7k Golang : Sort and reverse sort a slice of integers
+6.5k Golang : Command line ticker to show work in progress
+3.9k Golang : A program that contain another program and executes it during run-time
+44.3k Golang : Marshal and unmarshal json.RawMessage struct example
+6.3k Golang : Scanf function weird error in Windows
+14.4k Chrome : ERR_INSECURE_RESPONSE and allow Chrome browser to load insecure content
+9k CodeIgniter : Load different view for mobile devices
+10.3k Golang : Generate DSA private, public key and PEM files example
+10k Golang : Fix fmt.Scanf() on Windows will scan input twice problem
+7.8k Golang : GMail API create and send draft with simple upload attachment example
+4.5k Golang : Intercept, inject and replay HTTP traffics from web server