Function semantics

Recursive function calls

A recursive function calls itself directly or indirectly. Use a base case and progress toward it. Go does not guarantee tail-call optimization; deep recursion may exhaust stack resources. The example accepts nonnegative small integers. Example output: '10'.

Formal Syntax & Structure

go syntaxgo
func f(n int) int { ... f(n-1) ... }

Working Example

Example Snippetgo
package main
import "fmt"
func sum(n int) int {  if n <= 0 {    return 0  }  return n + sum(n-1)}func main() {  fmt.Println(sum(4))}
Go Reference