Chapter 5. on the list: Arrays

image

A whole lot of programs deal with lists of things. Lists of addresses. Lists of phone numbers. Lists of products. Go has two built-in ways of storing lists. This chapter will introduce the first: arrays. You’ll learn about how to create arrays, how to fill them with data, and how to get that data back out again. Then you’ll learn about processing all the elements in array, first the hard way with for loops, and then the easy way with for...range loops.

Arrays hold collections of values

A local restaurant owner has a problem. He needs to know how much beef to order for the upcoming week. If he orders too much, the excess will go to waste. If he doesn’t order enough, he’ll have to tell his customers that he can’t make their favorite dishes.

He keeps data on how much meat was used the previous three weeks. He needs a program that will give him some idea of how much to order.

image

This should be simple enough: we can calculate the average by taking the three amounts, adding them together, and dividing by 3. The average should offer a good estimate of how much to order.

image

The first issue is going to be storing the sample values. It would be a pain to ...

Get Head First Go now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.