Functions
I’m always delighted by the light touch and stillness of early programming languages. Not much text; a lot gets done. Old programs read like quiet conversations between a well-spoken research worker and a well- studied mechanical colleague, not as a debate with a compiler. Who’d have guessed sophistication bought such noise?
Richard P. Gabriel
Functions are the basic building blocks of Go programs; all interesting stuffhappens in them.
Here is an example of how you can declare a function:
type mytype int
func (p mytype) funcname(q int) (r,s int) { return 0,0 }
1 2 3 4 5 6
To declare a function, you use the func
keyword 1. You can optionally bind2 to a specific type called receiver (a functionwith a receiver is usually called a method). This willbe explored in . Next 3 you write the name of yourfunction. Here 4 we define that the variable q
of type int
is the inputparameter. Parameters are passed pass-by-value.The variables r
and s
5 are the named return parameters (((functions,named return parameters))) for this function. Functions in Go can have multiplereturn values. This is very useful to return a value and error. Thisremoves the need for in-band error returns (such as -1 for EOF
) and modifyingan argument. If you want the return parameters not to be named you only give thetypes: (int, int)
. If you have only one value to return you may omit theparentheses. If your function is a subroutine and does not have anything toreturn you may omit this entirely. Finally, we have the body 6 of thefunction. Note that return
is a statement so the braces around theparameter(s) are optional.
As said the return or result parameters of a Go function can be given names andused as regular variables, just like the incoming parameters. When named, theyare initialized to the zero values for their types when the function begins. Ifthe function executes a return
statement with no arguments, the current valuesof the result parameters are returned. Using these features enables you (again)to do more with less code.8
The names are not mandatory but they can make code shorter and clearer:they are documentation. However don’t overuse this feature, especially in longer functions where it might not be immediately apparent what is returned.
Functions can be declared in any order you wish. The compiler scans the entirefile before execution, so function prototyping is a thing of the past in Go. Godoes not allow nested functions, but you can work around this with anonymousfunctions. See the Section in this chapter. Recursivefunctions work just as in other languages:
func rec(i int) {
if i == 10 { 1
return
}
rec(i+1) 2
fmt.Printf("%d ", i)
}
Here 2 we call the same function again, rec
returns when i
has the value10, this is checked on the second line 1. This function prints: 9
8 7 6 5 4 3 2 1 0
, when called as rec(0)
.