Go Idioms

Errors Are Values

Go treats errors as return values that you check explicitly, allowing precise control over failure handling without exceptions.

In Go, errors are values returned by functions rather than exceptions thrown by the runtime. You handle them by checking the second return value and using errors.Is or errors.As to inspect specific error types.

func readFile(name string) ([]byte, error) {
    data, err := os.ReadFile(name)
    if err != nil {
        if errors.Is(err, os.ErrNotExist) {
            return nil, fmt.Errorf("file missing: %w", err)
        }
        return nil, err
    }
    return data, nil
}