Programming paths / Go

Go learning path

Build dependable Go services with explicit errors, context-aware operations, and simple concurrency.

Starter lesson

Return validation errors explicitly

Go functions commonly return a value and an error. Callers must decide how to respond, which keeps failure paths visible.

package main

import (
    "fmt"
)

func validatePort(port int) error {
    if port < 1 || port > 65535 {
        return fmt.Errorf("port %d is outside the valid range", port)
    }
    return nil
}

func main() {
    if err := validatePort(8080); err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println("Port is valid")
}

What to expect

Port is valid

Key idea: Handle returned errors at the point where the program can make a meaningful decision.

← Browse all programming paths