Go Functions


Go Functions

Functions in Go are self-contained blocks of code that perform specific tasks. They allow modular programming, code reusability, and better maintainability. In Go, functions can take arguments, return values, and even be used as first-class citizens.


1. Declaring a Function

A function in Go is defined using the func keyword, followed by the function name, parameters (if any), return type (if applicable), and a code block enclosed in curly braces {}.

Syntax:

func functionName(parameters) returnType {
    // Function body
}

2. Basic Function Example

package main

import "fmt"

// A function that neither accepts parameters nor returns a value.
func greet() {
    fmt.Println("Hello, Go!")
}

func main() {
    greet() // Calling the function
}

Output:

Hello, Go!

3. Function with Parameters

A function can accept input parameters to perform operations dynamically.

Example:

package main

import "fmt"

// Function with two integer parameters
func add(a int, b int) {
    sum := a + b
    fmt.Println("Sum:", sum)
}

func main() {
    add(5, 10) // Calling the function with arguments
}

Output:

Sum: 15

4. Function with Return Value

A function can utilize the return statement to deliver a value.

Example:

package main

import "fmt"

// Function returning an integer value
func multiply(x int, y int) int {
    return x * y
}

func main() {
    result := multiply(4, 3) // Function call with return value
    fmt.Println("Multiplication:", result)
}

Output:

Multiplication: 12

5. Multiple Return Values

Go functions can return multiple values, which is useful in various scenarios such as error handling.

Example:

package main

import "fmt"

// Function returning two values
func divide_num(a int, b int) (int, int) {
    quotient := a / b
    remainder := a % b
    return quotient, remainder
}

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

Output:

Quotient: 3 Remainder: 1

6. Named Return Values

Go allows defining return variables in the function signature itself.

Example:

package main

import "fmt"

// Function with named return values
func rectangle(dim1 int, dim2 int) (area int, perimeter int) {
    area = dim1 * dim2
    perimeter = 2 * (dim1 + dim2)
    return // Implicit/Automatically return of named values
}

func main() {
    a, p := rectangle(5, 3)
    fmt.Println("Area:", a, "Perimeter:", p)
}

Output:

Area: 15 Perimeter: 16

7. Variadic Functions

Go supports functions with a variable number of arguments using ... syntax.

package main

import "fmt"

// Function accepting variable number of integers
func sum(numbers ...int) int {
    total := 0
    for _, num := range numbers {
        total += num
    }
    return total
}

func main() {
    result_sum := sum_num(1, 2, 3, 4, 5)
    fmt.Println("Total Sum:", result_sum)
}

Output:

Total Sum: 15

8. Anonymous Functions

Functions can be defined without names, often used for short-lived operations.

Example:

package main

import "fmt"

func main() {
    // Anonymous function
    func() {
        fmt.Println("This is an anonymous function")
    }() // Immediate execution
}

Output:

This is an anonymous function

9. Functions as Values

Go allows assigning functions to variables and passing them as arguments.

Example:

package main

import "fmt"

func message() {
    fmt.Println("Hello from function variable!")
}

func main() {
    greet := message // Assign function to variable
    greet() // Invoke function via variable
}

Output:

Hello from function variable!

10. Higher-Order Functions

Functions can take other functions as inputs or return them as outputs.

Example:

package main

import "fmt"

// A function that receives another function as an argument.
func operate(a int, b int, operation func(int, int) int) int {
    return operation(a, b)
}

func main() {
    add := func(x, y int) int {
        return x + y
    }

    result := operate(7, 3, add)
    fmt.Println("Result:", result)
}

Output:

Result: 10

11. Closures

A function that references variables outside its scope is called a closure.

Example:

package main

import "fmt"

func counter() func() int {
    count := 0
    return func() int {
        count++
        return count
    }
}

func main() {
    increment := counter()
    fmt.Println(increment()) // 1
    fmt.Println(increment()) // 2
}

Output:

1
2

12. Defer in Functions

The defer statement postpones function execution until surrounding function exits.

Example:

package main

import "fmt"

func main() {
    defer fmt.Println("This is executed last")
    fmt.Println("This executes first")
}

Output:

This executes first
This is executed last

Conclusion

Go functions are powerful, enabling clean and structured programming. By leveraging features like multiple return values, closures, and function variables, Go developers can write efficient and readable code.

PreviousNext