Chapter 3. call me: Functions

image

You’ve been missing out. You’ve been calling functions like a pro. But the only functions you could call were the ones Go defined for you. Now, it’s your turn. We’re going to show you how to create your own functions. We’ll learn how to declare functions with and without parameters. We’ll declare functions that return a single value, and we’ll learn how to return multiple values so that we can indicate when there’s been an error. And we’ll learn about pointers, which allow us to make more memory-efficient function calls.

Some repetitive code

Suppose we need to calculate the amount of paint needed to cover several walls. The manufacturer says each liter of paint covers 10 square meters. So, we’ll need to multiply each wall’s width (in meters) by its height to get its area, and then divide that by 10 to get the number of liters of paint needed.

image
image

This works, but it has a couple problems:

  • The calculations seem to be off by a tiny fraction, and are printing oddly precise floating-point values. We really only need a couple decimal places of precision.

  • There’s a fair amount of repeated code, even now. This will get worse as we add more walls.

Both ...

Get Head First Go now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.