Chapter 6. Functions
A function (also known as a procedure or a subroutine) is an independent section of code that maps zero or more input parameters to zero or more output parameters. As illustrated in Figure 6-1, functions are often represented as a black box.
Figure 6-1. A black box function
In previous chapters, the programs we have written in Go have used only one function:
funcmain(){}
We will now begin writing programs that use more than one function.
Your Second Function
Let’s take another look at the following program from Chapter 5:
funcmain(){xs:=[]float64{98,93,77,82,83}total:=0.0for_,v:=rangexs{total+=v}fmt.Println(total/float64(len(xs)))}
This program computes the average of a series of numbers. Finding the average like this is a very general problem, so it’s an ideal candidate for definition as a function.
The average function will need to take in a slice of float64s and return one float64. Insert this before the main function:
funcaverage(xs[]float64)float64{panic("Not Implemented")}
Functions start with the keyword func, followed by the function’s name. The parameters (inputs) of the function are defined like this: name type, name type, …. Our function has one parameter (the list of scores) that we named xs. After the parameters, we put the return type. Collectively, the parameters and the return type are known as the function’s ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access