Tsallaka zuwa abun ciki
Justice Tech School

Parameters, Returns and Recursion

Parameters list name then type, and consecutive parameters of one type can share it. Named results act as variables. A function can call itself, which is recursion, as long as it has a base case.

Example
package main

import "fmt"

func rect(w, h int) (area, perimeter int) {
	area = w * h
	perimeter = 2 * (w + h)
	return
}

func factorial(n int) int {
	if n <= 1 {
		return 1
	}
	return n * factorial(n-1)
}

func main() {
	a, p := rect(3, 4)
	fmt.Println(a, p, factorial(5))
}

Result

12 14 120

Exercise

A function that calls itself uses...

Quiz Test

What does a recursive function need?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.