Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

Go Lang - Functions

Defining and Using Functions in Go

This guide provides examples and explanations of defining and using functions in the Go programming language.

Key Points:

  • Functions in Go are defined using the func keyword followed by the function name, parameters (if any), return type (if any), and function body.
  • Go supports multiple return values from a function, which allows for flexible and concise function definitions.
  • Functions in Go can also be used as first-class citizens, meaning they can be assigned to variables, passed as arguments to other functions, and returned from other functions.

Defining Functions

Functions in Go can be defined with or without parameters and return values.


// Example: Function definition in Go
package main

import "fmt"

// Simple function without parameters and return value
func greet() {
    fmt.Println("Hello, World!")
}

// Function with parameters and return value
func add(a, b int) int {
    return a + b
}

func main() {
    greet()
    result := add(5, 3)
    fmt.Println("Result of addition:", result)
}
          

Returning Multiple Values

Go allows functions to return multiple values, which can be useful in various scenarios.


// Example: Function returning multiple values in Go
package main

import "fmt"

func divide(dividend, divisor float64) (float64, error) {
    if divisor == 0 {
        return 0, fmt.Errorf("division by zero")
    }
    quotient := dividend / divisor
    return quotient, nil
}

func main() {
    result, err := divide(10.0, 2.0)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    fmt.Println("Result of division:", result)
}
          

Using Functions as Values

In Go, functions can be assigned to variables, passed as arguments to other functions, and returned from other functions.


// Example: Using functions as values in Go
package main

import "fmt"

func add(a, b int) int {
    return a + b
}

func subtract(a, b int) int {
    return a - b
}

func operate(operation func(int, int) int, x, y int) int {
    return operation(x, y)
}

func main() {
    fmt.Println("Result of addition:", operate(add, 5, 3))
    fmt.Println("Result of subtraction:", operate(subtract, 5, 3))
}
          

Summary

This guide provided examples and explanations of defining and using functions in Go, including function definitions, returning multiple values, and using functions as values. By mastering these concepts, you can write efficient and modular Go programs.