Golang: Arrays of Strings

This post is going to be about Golang, arrays and strings. In Go we have more than simple arrays that we know from JavaScript or PHP. They are basically divided into the following:

arrays

slices

maps

This was confusing to me at first, because in basically every language I knew I could change the length of an array by just pushing things to it. Not so; in Go.

Arrays can’t change length

The solution to that is not to create a very long array every time, but to use arrays when appropriate.

If you know you’re going to program a score board for a video game (Let’s say Mario Kart or Snowboard Kids), you know you’ll have a fixed amount of positions. Either 12 for Mario Kart or 4 for Snowboard Kids. You know the length of the array from the start and create an array that has 12 entries and they can contain a player name:

First we initialise the array with 12 entries and their contents are going to be of type string. Wario wins and Mario comes in last, because he’s a massive loser and a lousy, but loveable protagonist.

In the end we have a simple for loop to output all the entries.

When we run this program, we should see the following output:

# go run array-test.go
Wario finished as number 1
Luigi finished as number 2
Peach finished as number 3
Yoshi finished as number 4
finished as number 5
finished as number 6
finished as number 7
finished as number 8
finished as number 9
finished as number 10
finished as number 11
Mario finished as number 12

Note that due to my laziness, the entries 4 to 10 or array indexes 5 to 11 are empty and therefor don’t output anything, but the print statement still occurs. If we change the print statement to the following, we can easily show why that is. Let’s change the line to the following:

fmt.Printf("%#v finished as number %d\n", score_board[i], i + 1)

This should output the lines below:

"Wario" finished as number 1
"Luigi" finished as number 2
"Peach" finished as number 3
"Yoshi" finished as number 4
"" finished as number 5
"" finished as number 6
"" finished as number 7
"" finished as number 8
"" finished as number 9
"" finished as number 10
"" finished as number 11
"Mario" finished as number 12

Emptyness! More precisely, empty strings! Empty strings are boring and liveless, exactly like the underwear you think of if this is the first language you learn, or if you’re a typical teenager.

Without assigning a value to an index of a Go array of strings, the default value is an empty string.

In the next post about Go we’re going to have a look at slices and I will do my best to stay away from the pizza metaphors.