NASutils Knowledge BaseUnofficialPolski

Go · lesson 10 of 30 · Decisions and loopsWrite functions

A function names the types of its parameters and results and may return several values. ...int takes any number of whole numbers.

Programming on the NAS › Go in 30 lessons

10-functions.go Download 10-functions.go

package main

import "fmt"

func human(bytes float64) string {
	units := []string{"B", "KiB", "MiB", "GiB", "TiB"}
	i := 0
	for bytes >= 1024 && i < len(units)-1 {
		bytes /= 1024
		i++
	}
	return fmt.Sprintf("%.1f %s", bytes, units[i])
}

// A function can return more than one value
func split(total, part int) (percent, rest int) {
	return part * 100 / total, total - part
}

// ...int takes any number of values
func sum(numbers ...int) int {
	s := 0
	for _, n := range numbers {
		s += n
	}
	return s
}

func main() {
	fmt.Println(human(900))
	fmt.Println(human(52428800))
	percent, rest := split(120, 93)
	fmt.Println(percent, "percent used,", rest, "free")
	fmt.Println(sum(8, 8, 12, 1))
}

Terminal

$ ./10-functions
900.0 B
50.0 MiB
77 percent used, 27 free
29

Exercise

Write min3, which returns the lowest of three numbers.

TurboShell does not contain Go. These programs are made in Bucket & Code with its Go runtime; the finished file runs on the NAS without Go.