Skip to content

Instantly share code, notes, and snippets.

@CypherpunkSamurai
Created September 30, 2021 09:21
Show Gist options
  • Save CypherpunkSamurai/f884dbc947e309eb972c0df46b3b5b30 to your computer and use it in GitHub Desktop.
Save CypherpunkSamurai/f884dbc947e309eb972c0df46b3b5b30 to your computer and use it in GitHub Desktop.
Slices and Arrays in Golang

Slices and Arrays in Golang

This gist explains difference between arrays and slices in Golang

Usually what we understand with an array is that it stores objects with same types in locations called indexes (starting at 0).

so, [1,2,3,4,5] contains numbers (integers) from 1 to 5. each of them at indexes 0,1,2,3,4 respectively.

In golang there are two types of arrays like other languages.

arrays of fixed and dynamic sizes.

Fixed sized arrays are called, well.... Arrays

Dynamic sized arrays are called slices.

Let's see an example how to define an array and a slice

Array

a := [5]int{1,2,3,4,5}
// or
// var a := make([]int, 5)
// then fill the values for each index with loop

fmt.Printf("a: %+v\n", a)

Slices

b := []int

// slices can be appended
b = append(b, 1)
b = append(b, 2)
b = append(b, 3)

fmt.Println(b)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment