From PHP to Go: Arrays

This is a quick and dirty article about arrays, slices, and maps in Go for all those who come from PHP and are getting started with this fantastic language.

Table of contents

  1. The Basics
  2. Arrays in Go
  3. Slices in Go
  4. Maps in Go
  5. Iterate over arrays, slices, and maps in Go
  6. Subarrays with different types

1. The basics

There are two essential things you must know:

  1. In Go, you have three kinds of similar structures to PHP arrays: arrays, slices, and maps. We will see the difference later.
  2. In Go, the elements of an array have the same type. This type must be defined when you declare the variable for this array/slice/map.

The main difference between those kinds of structures is if the length of the array is fixed or not and if they have Key/Value pairs.

Array Slice Maps
Length Fixed Variable Variable
Key/Value No No Yes

2. Arrays in Go

Let’s say we want to declare an array of type string to save the days of the week:

See how there is a seven between the brackets indicating the number of elements it will contain. Once it is declared, you can’t change the number of items on it, but you can change the values.

Arrays as such are rarely used in Go due to their fixed length.

3. Slices in Go

Slices work like arrays as explained above, but they have variable length.

For declaring the same array as above, but as a slice, we simply omit the number between the brackets:

Since there is no fixed length, we can append new items to the slice:

And we can also delete items from the slice. If we want to remove the item of index 1 (“New Monday”):

Note that, as in the code above, we can get some items of any slice (and arrays) using the brackets after the variable :

To know the number of elements in any slice, use the function len()

4. Maps in Go

If you need to use key/value pairs, then you need to use maps.

For instance, if you need to replicate this PHP array in Go:

You would need to define a map of key type string and value type string. You can use one of those ways:

Since now we have key/value pairs, you can append elements without using append:

5. Iterate over arrays, slices, and maps in Go

The most common way is to use range

6. Subarrays with different types

What if I need an array of arrays, also with variables of different type, like I can do on PHP?

You can create “maps of maps”. For instance, let’s say you need to have this PHP array in Go:

You could create such a map doing this:

If you need to have different variables of different type in your subarrays, you need to define new variable types using structs:

That’s all Folks! ;)


Quick and dirty article about arrays, slices and maps in Go for all those who come from PHP

Antonio Sánchez

PHP Go

485 Words

Mar 2, 2019