Functions in Go

Introduction to Functions

Functions in Go are blocks of reusable code that perform a specific task. They allow developers to modularize programs, reducing redundancy and improving readability. A function in Go follows a simple syntax and can take inputs, process them, and return outputs.

Defining a Function

A function in Go is defined using the func keyword followed by the function name, parameters (if any), and the function body. Below is an example of a basic function that prints a message.

package main

import "fmt"

func greet() {
    fmt.Println("Hello, Go!")
}

func main() {
    greet()
}

This function greet() prints a simple greeting message when called inside the main() function.

Function with Parameters

Functions can accept parameters to perform operations on dynamic values. Below is an example where we pass two integers to a function.

package main

import "fmt"

func add(a int, b int) {
    sum := a + b
    fmt.Println("Sum:", sum)
}

func main() {
    add(5, 10)
}

Here, the function add() takes two integers as arguments, calculates their sum, and prints the result.

Function with Return Value

Instead of printing the result directly, a function can return a value that can be stored and used later.

package main

import "fmt"

func multiply(a int, b int) int {
    return a * b
}

func main() {
    result := multiply(4, 5)
    fmt.Println("Product:", result)
}

Here, multiply() returns the product of two numbers, which is then stored in a variable result and printed.

Multiple Return Values

Go allows functions to return multiple values, making it easy to return related data in a single function call.

package main

import "fmt"

func divide(a int, b int) (int, int) {
    quotient := a / b
    remainder := a % b
    return quotient, remainder
}

func main() {
    q, r := divide(10, 3)
    fmt.Println("Quotient:", q, "Remainder:", r)
}

Here, the divide() function returns both the quotient and remainder, which are captured separately.

Anonymous Functions

Go supports anonymous functions, which are functions without a name. These are useful for short-lived operations.

package main

import "fmt"

func main() {
    sum := func(a int, b int) int {
        return a + b
    }
    fmt.Println("Sum:", sum(3, 7))
}

Here, we define an anonymous function and assign it to the variable sum, which is then called immediately.

Conclusion

Functions in Go help structure code efficiently, reducing repetition and increasing maintainability. They can take parameters, return values, and even return multiple values. Additionally, Go supports anonymous functions for short-term operations.

In the next lesson, we will explore Arrays and Slices in Go, which are used to store and manipulate collections of data.