An Introduction to Go Programming Language

Original article was published by Dasaradh S K on Artificial Intelligence on Medium


Structs, arrays, slices, and maps

Structs

Go’s structs are collections of fields. They’re useful for grouping data together to form records.

Struct fields are accessed using a dot. Below is an example of the struct.

Arrays

The expression var a [10]int declares a variable as an array of 10 integers. Arrays cannot be resized, because an array’s length is part of its type.

We can set a value at an index using the array[index] = value , and get value with array[index].

Arrays can also be declared and initialized in one line. By default an array is zero-valued

Slices

A slice is formed by specifying two indices, a low and high bound, separated by a colon a[low : high]

Unlike an array which has a fixed size, a slice is dynamically-sized. Slices are much more common than arrays.

The builtin append function, adds one or more new values to the slice.

Maps

Maps are Go’s built-in associative data type (called dicts in some languages). A map maps keys to values. To create an empty map, use the builtin make: make(map[key-type]val-type)

Key/value can be set using name[key] = val syntax. The value for a key can be get using name[key].

Printing a map will show all of its key/value pairs. Below is an example of using maps.