Recently I wrote an introduction to using Go, looking at what it is, how to install it, and how to get your environment ready. The article finished up by stepping through a small application covering the Go basics of variables, output, functions and structs.
In today’s article, we’ll build on that foundation, by looking at a few new concepts; specifically:
- Arrays & Slices
- Maps
- Methods
Arrays & Slices
There’s many ways in which you can initialize an array in Go. Let’s have a look through 5 examples:
var numberList [5]int
var stringList [10]string
var float64List [15]float64
Here, we’ve created three empty arrays, of different types (int, string and float64) and different sizes (5, 10 and 15).
x := [5]float64{ 98, 93, 77, 82, 83 }
Here, we’ve created an array, 5 elements in size of type float64, initializing it at the same time.
y := [...]int{ 98, 93, 77, 82, 83 }
Here, we’ve created an array of type int, but not specified the size. Instead, we’ve passed in ...
, and a range of values. When initializing the array this way, it will determine the size from the number of elements provided.
If you are familiar with dynamic languages, such as Python, PHP and Ruby, you’ll be used to creating arrays of a fixed size, with elements of a mixed or same type, but also be able to dynamically add and remove elements as you go along. Here’s a PHP example:
Continue reading %Arrays, Slices and Basic OOP in Go%