You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Functions are the building blocks of Go programs. Go functions support multiple return values, named return values, variadic parameters, and first-class function values. Combined with Go's explicit error handling pattern, functions form the backbone of idiomatic Go code.
func greet(name string) string {
return "Hello, " + name
}
func add(a, b int) int {
return a + b
}
When consecutive parameters share a type, you only need to specify the type once.
Go functions can return multiple values — this is fundamental to the language:
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, fmt.Errorf("cannot divide by zero")
}
return a / b, nil
}
// Usage:
result, err := divide(10, 3)
if err != nil {
log.Fatal(err)
}
fmt.Println(result) // 3.3333...
Multiple return values are the foundation of Go's error handling pattern.
func divide(a, b float64) (result float64, err error) {
if b == 0 {
err = fmt.Errorf("cannot divide by zero")
return // "naked" return — returns named values
}
result = a / b
return
}
Named return values are pre-declared variables. A bare return returns them automatically. Use sparingly — they can reduce readability in longer functions.
A function that accepts a variable number of arguments:
func sum(nums ...int) int {
total := 0
for _, n := range nums {
total += n
}
return total
}
// Usage:
sum(1, 2, 3) // 6
sum(1, 2, 3, 4, 5) // 15
// Spread a slice:
nums := []int{1, 2, 3}
sum(nums...) // 6
The variadic parameter must be the last parameter in the function signature.
Functions are first-class values in Go — they can be assigned to variables, passed as arguments, and returned from other functions:
// Assign to a variable
add := func(a, b int) int { return a + b }
fmt.Println(add(3, 4)) // 7
// Pass as an argument
func apply(f func(int, int) int, a, b int) int {
return f(a, b)
}
result := apply(add, 10, 20) // 30
An anonymous function that captures variables from its surrounding scope:
func counter() func() int {
count := 0
return func() int {
count++
return count
}
}
c := counter()
fmt.Println(c()) // 1
fmt.Println(c()) // 2
fmt.Println(c()) // 3
Go does not have exceptions. Instead, errors are values returned from functions:
type error interface {
Error() string
}
Any type that implements the Error() string method satisfies the error interface.
import "errors"
import "fmt"
// Simple error
err := errors.New("something went wrong")
// Formatted error
err := fmt.Errorf("user %d not found", userID)
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.