Understand the contract

A Go function names a computation with declared parameter and result types. Start with a small contract: what input is valid, what value is returned and whether the function changes external state. That contract makes a function easier to reuse and gives a test a concrete expectation.

This block builds from ordinary functions to multiple results, variadic parameters, error values, methods and interfaces. Keep input validation close to the operation that understands the rule. For an expected failure, return an error; do not force every caller to recover from a panic.

Work through the example

The example defines add as a function of two ints returning one int. Both parameters share a type declaration, and return supplies the result. Calling add does not change a or b in the caller. Local names inside the function are independent of the caller’s variable names.

package main

import "fmt"

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

func main() { fmt.Println(add(2, 3)) }

Watch this boundary

A function with many unrelated boolean parameters is difficult to call correctly. Before adding an options struct or interface, ask whether the function performs several unrelated jobs. Prefer a clear operation and explicit arguments; introduce abstractions after you can show the repeated need.

Practice with a changed input

Write a function that computes a rectangle’s area. Define what should happen for negative dimensions, then use the errors lesson to express that decision without printing inside the calculation.

References & further reading

Need help with your Go backend?

I work with engineering teams on focused Go and Kubernetes platform engagements, with limited consulting availability.

Explore Go consulting services