spinner
·
Alan Donovan
One go statement keeps a terminal spinner turning while main grinds through a slow computation. Nobody stops the spinner; when main returns, the program ends and takes it along.
func main() {
go spinner(100 * time.Millisecond)
const n = 45
fibN := fib(n) // slow
fmt.Printf("\rfib(%d) = %d\n", n, fibN)
}
func spinner(delay time.Duration) {
for {
for _, r := range `-\|/` {
fmt.Printf("\r%c", r)
time.Sleep(delay)
}
}
}
func fib(x int) int {
if x < 2 {
return x
}
return fib(x-1) + fib(x-2)
}
Source: gopl.io/ch8/spinner from The Go Programming Language by Alan Donovan and Brian Kernighan.