Understand the contract

An error in Go is a value implementing the Error() string method. A nil error commonly signals success. Functions that can fail often return (result, error), letting the caller decide whether to retry, report the problem or stop. Check the error before using a result that depends on success.

Validation belongs at the point that knows the rule. divide rejects a zero divisor and returns a descriptive error. The caller prints that error once and returns. A library function should usually return the failure rather than log and return it too, which often produces duplicate reports.

Work through the example

The example succeeds with ten divided by two and prints five. Changing the divisor to zero follows the error branch. The zero result accompanying an error is not a valid quotient. Naming that convention in the function contract helps callers avoid consuming partial or placeholder results.

package main

import (
    "errors"
    "fmt"
)

func divide(a, b float64) (float64, error) {
    if b == 0 { return 0, errors.New("divisor must be nonzero") }
    return a / b, nil
}

func main() {
    result, err := divide(10, 2)
    if err != nil { fmt.Println(err); return }
    fmt.Println(result)
}

Watch this boundary

Do not use panic for ordinary malformed input that callers can reasonably handle. Panic is appropriate for different classes of failure and unwinds the stack until recovered or the program exits. Returning an error keeps expected failures in the function’s visible API and makes them straightforward to test.

Practice with a changed input

Test positive, negative and zero divisors. Change the caller so it adds operation context when displaying a failure while leaving divide independent of console output.

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