NASutils Knowledge BaseUnofficialPolski

Go · lesson 16 of 30 · Data, functions and the command lineUse an interface

A type with the method Check() (bool, string) fits the interface, so one loop handles them all.

Programming on the NAS › Go in 30 lessons

16-interfaces.go Download 16-interfaces.go

package main

import "fmt"

// Every type with this Check method fits
type Checker interface {
	Check() (ok bool, text string)
}

type Space struct{ Percent int }
type Heat struct{ Temp int }

func (s Space) Check() (bool, string) {
	return s.Percent < 90, fmt.Sprintf("%d percent used", s.Percent)
}

func (h Heat) Check() (bool, string) {
	return h.Temp < 50, fmt.Sprintf("%d C", h.Temp)
}

func main() {
	checks := []Checker{Space{75}, Heat{53}, Space{93}}
	for _, c := range checks {
		ok, text := c.Check()
		fmt.Printf("%-5t %s\n", ok, text)
	}
}

Terminal

$ ./16-interfaces
true  75 percent used
false 53 C
false 93 percent used

Exercise

Add a third check, for the age of a backup.

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.