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.
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.