O'Reilly logo

Head First Go by Jay McGavren

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

5 arrays

On the List

Images

A whole lot of programs deal with lists of things. Lists of addresses. Lists of phone numbers. Lists of products. Go has two ways of storing lists built-in. 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 how much to order.

Images

This should be simple enough: we can calculate an 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.

Images

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required