ch30.md 1.1 KB

Chapter 30. Strict functions

As an experimental mode called strictFuncs a stricter definition of “side effect” is available. In addition to the existing rule that a side effect is calling a function with side effects the following rule is also enforced: A store to the heap via a ref or ptr indirection is not allowed. For example: {.experimental: "strictFuncs".} type

Node = ref object
  le, ri: Node
  data: string

func len(n: Node): int =

# valid: len does not have side effects
var it = n
while it != nil:
  inc result
  it = it.ri

func mut(n: Node) =

n.data = "yeah" # short for: m[].data = "yeah"
# Error: 'mut' can have side effects

Mutations via var T and out T parameters continue to be allowed in a strict func. Hence a prototype such as func addT is valid and can be used in the following func: func tokenize(input: string): seq[string] =

result = @[]
for w in splitWhitespace(input): result.add w
                                                                            217

The mutation that add performs does not count as a side effect and so tokenize can be a func.