Functions in Go
Guide to Go functions: declaration, execution flow, parameters, variadics, function values, closures, and higher-order functions.
Function Basics & Execution Flow
Functions encapsulate reusable logic. When a function is called, execution jumps into the function and returns back after completion.
1. Creating and Calling a Function
Define once, call many times.
2. Function Execution Flow
Understand call order.
Parameters & Arguments
Go does not have optional parameters. We can simulate them using a struct: the caller sets only the fields they need, and omitted fields get their zero value. A struct also gives named, order-independent arguments.
1. Zero Value as Default (Single Parameter)
For one parameter, check zero value and set a fallback inside the function.
2. Optional Parameters Using a Struct
Pass a struct; caller sets only the fields they need. Omitted fields are zero-valued.
3. Optional Parameters Using Pointer Fields
Use *T in the struct: nil means not set; non-nil means the caller provided a value. Distinguishes "omitted" from "set to zero".
Variadic Parameters
Variadic parameters collect arguments into a slice. Use ...T as the last parameter.
1. Variadic Parameters
Unlimited inputs as a slice.
2. Passing a Slice to Variadic Parameters
Spread the slice with ...
Function Values & Literals
Go supports function values: you can assign functions to variables and pass them around. Anonymous functions are function literals without a name.
1. Function Values (Anonymous Functions)
Functions assigned to variables.
2. Running a Function Immediately
Call a literal right after defining it.
Closures & State
Closures allow functions to access variables from outer scopes. A function literal can capture variables and retain state across calls.
1. Stateful Closure
Maintain private state.
Higher-Order Functions (Custom Implementation)
A higher-order function takes a function as an argument, returns a function, or both. We implement map, filter, forEach, find, findIndex, some, every, reduce, and group using loops.
1. What is a Higher-Order Function?
Functions that operate on other functions.
2. Creating map from Scratch
Transform each element.
3. Creating filter from Scratch
Select elements conditionally.
4. Creating forEach from Scratch
Execute logic for each element.
5. Creating find from Scratch
Find first matching element.
6. Creating findIndex from Scratch
Find index of first matching element.
7. Creating some from Scratch
Check if at least one element matches.
8. Creating every from Scratch
Check if all elements match.
9. Creating reduce from Scratch
Accumulate values into one.
10. Creating group from Scratch
Group elements by multiple rules.