Control Flow
Control flow: mostly familiar, one surprise
Section titled “Control flow: mostly familiar, one surprise”TypeScript has if, for, for...of, for...in, while, do...while, and switch. Go has if, for, and switch — and for does the job of all loop types. There is no while keyword. Once you see it, you’ll appreciate the simplicity.
if / else
Section titled “if / else”Go’s if is close to TypeScript’s, but there are no parentheses around the condition, and the braces are always required.
if (score > 90) { console.log("A");} else if (score > 70) { console.log("B");} else { console.log("C");}if score > 90 { fmt.Println("A")} else if score > 70 { fmt.Println("B")} else { fmt.Println("C")}The single for loop
Section titled “The single for loop”Go’s for covers every looping pattern:
// C-stylefor (let i = 0; i < 5; i++) { ... }
// whilewhile (condition) { ... }
// infinitewhile (true) { ... }
// for...offor (const item of items) { ... }// C-stylefor i := 0; i < 5; i++ { ... }
// while (drop init and post)for condition { ... }
// infinitefor { ... }
// range (like for...of)for i, item := range items { ... }switch
Section titled “switch”Go’s switch does not fall through by default (unlike JavaScript/TypeScript where you need break). Each case is independent. You can use fallthrough explicitly if you want the old behaviour.
switch (day) { case "Mon": case "Tue": console.log("Weekday"); break; // required! case "Sat": case "Sun": console.log("Weekend"); break; default: console.log("Unknown");}switch day {case "Mon", "Tue", "Wed", "Thu", "Fri": fmt.Println("Weekday") // no break neededcase "Sat", "Sun": fmt.Println("Weekend")default: fmt.Println("Unknown")}range iterates over slices, maps, strings, and channels. For a slice it gives you the index and value; use _ to discard either.
const nums = [10, 20, 30];
// index + valuenums.forEach((v, i) => console.log(i, v));
// value onlyfor (const v of nums) { console.log(v); }nums := []int{10, 20, 30}
// index + valuefor i, v := range nums { fmt.Println(i, v)}
// value only (discard index)for _, v := range nums { fmt.Println(v)}Try it
Section titled “Try it”package main
import "fmt"
func classify(n int) string { switch { case n < 0: return "negative" case n == 0: return "zero" case n < 10: return "small" default: return "large" }}
func main() { nums := []int{-3, 0, 7, 42} for _, n := range nums { fmt.Printf("%d is %s\n", n, classify(n)) }}Loading Go runtime (first run only, ~8 MB)…