From the course: Learning Go

Store ordered values in arrays - Go Tutorial

From the course: Learning Go

Store ordered values in arrays

- [Instructor] Like other C-style languages, an array in Go is an ordered collection of values or references. I'll describe their basic features but also suggest right away that it's better to use slices than arrays to represent ordered collections of values. It's important though, to understand arrays before you get to slices. I'm starting in a fresh version of the main .go file in the practice directory and I'll create a new variable named colors. And I'll say that this is going to be an array of three strings. In Go you start with the number of items in the array wrapped in brackets and then the type of the values in the array. Now I can explicitly set each individual value like this. I'll say colors, open bracket, zero close bracket equals red. Now I'm going to make a couple copies of that line and I'll set colors one and two and the values to green and blue. Now I'll output that value by simply passing the array into the print line function. And when I run the code, the output is red, green, blue. The three items in the array wrapped in the brackets. If I want to access one of those values I can use the array index. The index always starts at zero, not one. So if I say zero, I mean the first item in the array. And when I run that, I get red. Notice that you're using the equals operator, not colon equals to assign the arrays individual values. And that's because the array type has already been declared and it doesn't have to be inferred. You can also declare an array and its values in a single statement. This time I'll create a variable called numbers and I'll give it a value that starts with bracket five close bracket, and I'll set the type to int. And then I'll create a pair of braces and then a series of values as a comma delimited list. Then I'll use fmt.println and I'll put numbers. And there's the result. Once again, the output wraps the values in brackets and lists them without the commas. You can find the number of items in an array with the built-in len or length function wrapped around the array identifier. So I'll put fmt.println, So I'll put a string of number of colors and then the length of the colors array. And then I'll also do the same thing for the numbers array. And I see that there are three colors. I'll fix this label to number of numbers and run the code again. And now I see that there were three colors and five numbers. In Go an array is an object. And like all objects if you pass it to a function, a copy will be made of the array. But storing the data is just about all you can do with the arrays. You can't easily sort them and you can't add or remove items that runtime. For those features and more, you should package your order data in slices instead of a arrays. And I'll talk about slices next.

Contents