Programming

Go programming language

Errors

A simple example on how to return a custom error from a function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package grains

import "errors"

// Square computes grains numbers on each square of a chessboard
// where it each amount doubles previous amount existing on previous square
func Square(n int) (uint64, error) {
  var grains uint64
	
  // Zero or negative numbers through an error
  if n <= 0 || n > 64 {
    return 0, errors.New("Square: cannot process such number")
  }

  // Positive gets calculated
  for i := 1; i <= n; i++ {
    if i > 1 {
      grains = 2 * grains
    } else {
      grains = 1
    }
  }
  return grains, nil
}

Guides