Go has ...

  • arrays and slices : both are ordered collections of a single type. Not as flexible as Python lists.
  • maps : key-value pair data structure of a fixed types. Not as flexible as Python dictionaries, because in Go, both the key's and value's types are fixed at declaration. In that sense, Go's structs are a little similar to Python dictionaries.
  • structs : A struct in Go allows us to create a custom sub-type (of struct type) that represents a group/collection of related fields of different types. It is somewhat like an object in OO languages. We can also attach functions to struct types.
  • interface : It is not a type in itself. But it's a mechanism to create our own custom types in Go.

Arrays and Slices

arrays have fixed size and slices don't. That's the difference. Declaration and initialisation is same.

var a [3]string // declares an array of size 3
var b []string  // declares a slice

c := [3]string  // delcares an array of size 3
d := []int      // delcares a slice

// declares and initialises an array of size 3
e := [3]string{"Books", "Pens", "Pencils"}
f := []string{"Books", "Pens", "Pencils"}   // declares and initialises a slice

// declares an array of size 3 and initialises the first element
g := [3]string{"Books"}
// declares an array of size 3 and initialises the first two elements
h := [3]string{"Books", "Pens"}

// declares and initialises an array of size 3
i := [...]string{"Books", "Pens", "Pencils"}

// can be initialised with indices also
// need not specify all indices. Also, indices need not be in order
k := [10]int{4, 7: 5, 3: 10}

This array syntax has some similarities to Java. See ...

// just declaring
int[] ages = new int[3];

// with initialisation
int[] age = {35, 36, 42};

Arrays are most commonly looped over with conventional for loop like .... for i : 0; i < len(arr); i++ {.

One interesting thing to note regarding Go collections, including arrays, slices and maps, is that they internally keep track of the length of the collection. They don't recalculate it everytime we call len() on the collection. So, calling len() on a collection in Go does not have any performance penalty. One similarity to note is even in Python, len() is a function, not a method (of lists).

Slices are arrays in the background. Go manages the array size internally. Slices can be expanded with append() function. Thinking of append(), Python has a similarly named method on lists ... append(). It takes only a single argumanet and also also it changes the parent list itself. In contrast, in Go, append() is a function, it takes variable number of arguments and it gives a new slice (does not change the parent slice).


Published

Category

Go

Tags