Skip to content

Go function syntax and patterns

In Go, functions are the primary building blocks used to execute blocks of code and organize logic.^[readme.md] They should be designed with a single purpose to facilitate easier testing and maintenance.^[readme.md]

Basic Syntax

A function is declared using the func keyword, followed by the function name, input parameters, and return outputs.^[readme.md] Unlike some languages where input and return lists are treated singly, Go functions can accept multiple inputs and return multiple outputs.^[readme.md]

A basic function signature follows this structure:

func functionName(inputType) (outputType) {
    // function body
    return result
}

Function Patterns

Abstraction and Encapsulation

Functions serve as a mechanism for data abstraction. The caller of a function does not need to know the internal logic or where the data originates (e.g., a database or a file); they simply interact with the function's inputs and outputs.^[readme.md]

For example, a function named getData might retrieve information from an external source, but to the caller, it is simply a function that returns specific data based on provided inputs.^[readme.md]

Input Parameters and Control Flow

Functions use input parameters to modify behavior or filter results.^[readme.md] For instance, an int parameter like customerId can be used within control flow structures (such as if/else blocks) to return specific data or handle different cases.^[readme.md]

Returning Collections

Functions are often used to return groups of data. As applications scale beyond single variables, functions can be adapted to return complex data structures:

  • Arrays: Functions can return fixed-size collections of a specific type (e.g., [2]string).^[readme.md]
  • Slices: To handle dynamic lists where the size is not known upfront, functions can return slices ([]string). This allows for the dynamic addition of elements using the append function.^[readme.md]
  • Structs: When data represents complex entities with multiple properties (e.g., a customer with a first name and last name), functions can return user-defined types defined by structs.^[readme.md]
  • [[Go Structs]]
  • [[Go Control Flow]]
  • [[Go Loops]]

Sources

  • 400-devops__09-Scripting-Language__golang__introduction__readme.md