Golang Tutorial
Fundamentals
Control Statements
Functions & Methods
Structure
Arrays & Slices
String
Pointers
Interfaces
Concurrency
Functions are at the core of any programming language, and Go is no exception. In Go, functions allow you to group code into reusable blocks. This tutorial will provide a comprehensive overview of functions in Go.
In its simplest form, a function can be defined without parameters and without a return type.
package main import "fmt" func greet() { fmt.Println("Hello, Gopher!") } func main() { greet() // Outputs: Hello, Gopher! }
Functions can take zero or more parameters. Here's how you can define a function with parameters:
func greetUser(name string) { fmt.Println("Hello,", name) } func main() { greetUser("Alice") // Outputs: Hello, Alice }
Functions can also return values. Here's an example:
func add(a int, b int) int { return a + b } func main() { sum := add(2, 3) fmt.Println("Sum:", sum) // Outputs: Sum: 5 }
Go uniquely supports multiple return values from a function. This feature is often used to return a result along with an error value:
func divide(a, b float64) (float64, error) { if b == 0 { return 0, fmt.Errorf("division by zero") } return a / b, nil }
Go supports named return values, which can clarify the intent of the return values:
func rectangleArea(width, height float64) (area float64) { area = width * height return }
Functions in Go can take a variable number of arguments, known as variadic functions:
func sum(nums ...int) int { total := 0 for _, num := range nums { total += num } return total }
Go supports the creation of anonymous functions, which can also be assigned to variables:
adder := func(a, b int) int { return a + b } fmt.Println(adder(2, 3)) // Outputs: 5
In Go, functions are first-class citizens. This means they can be passed around as values:
func apply(nums []int, op func(int) int) []int { result := make([]int, len(nums)) for i, n := range nums { result[i] = op(n) } return result } func increment(x int) int { return x + 1 } func main() { numbers := []int{1, 2, 3, 4} fmt.Println(apply(numbers, increment)) // Outputs: [2 3 4 5] }
The defer
keyword is used to schedule a function call to be run after the function completes:
func hello() { defer fmt.Println("World") fmt.Println("Hello") } func main() { hello() // Outputs: Hello\nWorld }
Functions in Go can be recursive, i.e., they can call themselves:
func factorial(n int) int { if n == 0 { return 1 } return n * factorial(n-1) } func main() { fmt.Println(factorial(5)) // Outputs: 120 }
This tutorial has given you an overview of functions in Go, from their basic usage to more advanced topics. As you continue your journey with Go, you'll find functions to be an essential tool in writing efficient and maintainable code.
Defining Functions in Golang:
func
keyword.package main import "fmt" // Function definition func greet() { fmt.Println("Hello, Golang!") } func main() { // Function call greet() }
Parameters and Return Values in Golang Functions:
package main import "fmt" // Function with parameters and return values func add(a, b int) int { return a + b } func main() { result := add(3, 4) fmt.Println("Sum:", result) }
Variadic Functions in Golang:
package main import "fmt" // Variadic function func sum(numbers ...int) int { result := 0 for _, num := range numbers { result += num } return result } func main() { total := sum(1, 2, 3, 4, 5) fmt.Println("Sum:", total) }
Anonymous Functions in Golang:
package main import "fmt" func main() { // Anonymous function assigned to a variable add := func(a, b int) int { return a + b } result := add(3, 4) fmt.Println("Sum:", result) }
Function Closures in Golang:
package main import "fmt" func closureExample() func() int { count := 0 // Closure return func() int { count++ return count } } func main() { counter := closureExample() fmt.Println(counter()) // Output: 1 fmt.Println(counter()) // Output: 2 }
Function Signatures and Declarations in Golang:
package main import "fmt" // Function with parameters and return values func add(a, b int) int { return a + b } func main() { // Function signature var sumFunc func(int, int) int // Function assignment sumFunc = add result := sumFunc(3, 4) fmt.Println("Sum:", result) }
Recursion in Golang Functions:
package main import "fmt" // Recursive function func factorial(n int) int { if n <= 1 { return 1 } return n * factorial(n-1) } func main() { result := factorial(5) fmt.Println("Factorial:", result) }
Error Handling in Golang Functions:
package main import ( "fmt" "errors" ) // Function with error handling func divide(a, b int) (int, error) { if b == 0 { return 0, errors.New("division by zero") } return a / b, nil } func main() { result, err := divide(10, 0) if err != nil { fmt.Println("Error:", err) } else { fmt.Println("Result:", result) } }