Go Functions
A function is a named block of code that does one job. You define it once and call it as often as you need. Functions keep programs organised, avoid repetition and make code easier to test.
Defining and calling a function
A function is declared with the func keyword, a name, a parameter list in parentheses and a body in braces.
package main
import "fmt"
func greet() {
fmt.Println("Welcome to the Go course!")
}
func main() {
greet()
greet()
}Welcome to the Go course!
Welcome to the Go course!
Functions can be declared in any order in a file — main can call greet even if greet is written below it.
Parameters and return values (preview)
Inputs are listed as name type. The type of the result goes after the parameter list. The next chapter covers this in depth.
package main
import "fmt"
func area(width float64, height float64) float64 {
return width * height
}
func shout(word string) string {
return word + "!"
}
func main() {
fmt.Println(area(3, 4.5))
fmt.Println(shout("Go"))
room := area(5, 4)
fmt.Println("Room size:", room, "m²")
}13.5
Go!
Room size: 20 m²
Functions are values
In Go, a function is a value like any other. You can store it in a variable, pass it to another function, or return it from a function. The type of a function is written like its signature: func(int) int.
package main
import "fmt"
func double(n int) int { return n * 2 }
func square(n int) int { return n * n }
// apply takes a function as its first parameter
func apply(f func(int) int, values []int) []int {
result := make([]int, 0, len(values))
for _, v := range values {
result = append(result, f(v))
}
return result
}
func main() {
nums := []int{1, 2, 3, 4}
fmt.Println(apply(double, nums))
fmt.Println(apply(square, nums))
op := square
fmt.Println(op(9))
}[2 4 6 8]
[1 4 9 16]
81
Anonymous functions
A function literal has no name. You can call it immediately or assign it to a variable. They are handy for small one-off pieces of logic, such as a comparison passed to a sort function.
package main
import (
"fmt"
"slices"
"strings"
)
func main() {
add := func(a, b int) int {
return a + b
}
fmt.Println(add(2, 3))
func(msg string) {
fmt.Println("Called right away:", msg)
}("hi")
words := []string{"kiwi", "fig", "banana", "plum"}
slices.SortFunc(words, func(a, b string) int {
return len(a) - len(b) // shortest first
})
fmt.Println(words)
fmt.Println(strings.Map(func(r rune) rune { return r + 1 }, "HAL"))
}5
Called right away: hi
[fig kiwi plum banana]
IBM
Closures
An anonymous function can use variables from the scope around it. It captures those variables — it keeps them alive and can change them, even after the outer function has returned. Such a function is called a closure.
package main
import "fmt"
func counter() func() int {
count := 0
return func() int {
count++
return count
}
}
func main() {
next := counter()
fmt.Println(next(), next(), next())
other := counter() // a fresh, independent count
fmt.Println(other())
}1 2 3
1
| Concept | Example |
|---|---|
| Named function | func add(a, b int) int { return a + b } |
| Function type | func(int, int) int |
| Function variable | op := add |
| Anonymous function | func(x int) int { return x * 2 } |
| Closure | an anonymous function that uses outer variables |
Tip: Keep functions short and focused. A good rule: if you cannot describe what a function does in one sentence without "and", split it.
Test yourself
Which keyword declares a function in Go?
functiondeffuncfn
What is the type of func(s string) int { return len(s) }?
funcfunc(string) intintstring -> int
What is a closure?
- A function that never returns
- A function that captures variables from its surrounding scope
- A function with no parameters
- The last function in a file