Functions
are central in Go. We’ll learn about
functions with a few different examples.
packagemain
import"fmt"
Here’s a function that takes two
int
s and returns
their sum as an
int
.
funcplus(aint,bint)int{
Go requires explicit returns, i.e. it won’t
automatically return the value of the last
expression.
returna+b}
When you have multiple consecutive parameters of
the same type, you may omit the type name for the
like-typed parameters up to the final parameter that
declares the type.
funcplusPlus(a,b,cint)int{returna+b+c}
funcmain(){
Call a function just as you’d expect, with
name(args)
.
res:=plus(1,2)fmt.Println("1+2 =",res)
res=plusPlus(1,2,3)fmt.Println("1+2+3 =",res)}
$ go run functions.go
1+2 = 3
1+2+3 = 6
There are several other features to Go functions. One is
multiple return values, which we’ll look at next.