Go · lesson 8 of 30 · Decisions and loopsChoose with switch
switch compares a value, or takes the first true case. A case ends by itself.
08-switch.go Download 08-switch.go
package main
import (
"fmt"
"path/filepath"
"strings"
)
func kind(file string) string {
switch strings.ToLower(filepath.Ext(file)) {
case ".jpg", ".png":
return "photo"
case ".mov", ".mp4":
return "film"
case "":
return "no ending"
default:
return "other"
}
}
func main() {
for _, file := range []string{"beach.JPG", "trip.mp4", "notes.txt", "README"} {
fmt.Printf("%-10s %s\n", file, kind(file))
}
free := 12
switch { // without a value, the first true case wins
case free < 5:
fmt.Println("critical")
case free < 20:
fmt.Println("low")
default:
fmt.Println("fine")
}
}
Terminal
$ ./08-switch
beach.JPG photo
trip.mp4 film
notes.txt other
README no ending
lowExercise
Add .mp3 and .flac as music.
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.