Golang Tutorial

Fundamentals

Control Statements

Functions & Methods

Structure

Arrays & Slices

String

Pointers

Interfaces

Concurrency

What are the Functions in Golang?

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.

1. Basic Function Definition

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!
}

2. Function with Parameters

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
}

3. Function Returning a Value

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
}

4. Multiple Return Values

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
}

5. Named Return Values

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
}

6. Variadic Functions

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
}

7. Anonymous and Lambda Functions

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

8. Functions as First-Class Citizens

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]
}

9. Deferred Function Calls

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
}

10. Recursion

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
}

Conclusion

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.

  1. Defining Functions in Golang:

    • Functions in Golang are defined using the func keyword.
    • Example:
      package main
      
      import "fmt"
      
      // Function definition
      func greet() {
          fmt.Println("Hello, Golang!")
      }
      
      func main() {
          // Function call
          greet()
      }
      
  2. Parameters and Return Values in Golang Functions:

    • Functions can take parameters and return values.
    • Example:
      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)
      }
      
  3. Variadic Functions in Golang:

    • Variadic functions accept a variable number of arguments.
    • Example:
      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)
      }
      
  4. Anonymous Functions in Golang:

    • Anonymous functions don't have a name and can be assigned to variables.
    • Example:
      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)
      }
      
  5. Function Closures in Golang:

    • Closures capture and remember the scope of variables.
    • Example:
      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
      }
      
  6. Function Signatures and Declarations in Golang:

    • Function signatures define the function's name, parameters, and return types.
    • Example:
      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)
      }
      
  7. Recursion in Golang Functions:

    • Recursion involves a function calling itself.
    • Example:
      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)
      }
      
  8. Error Handling in Golang Functions:

    • Functions can return an error as the last return value.
    • Example:
      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)
          }
      }