Skip to content

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.

Go’s if is close to TypeScript’s, but there are no parentheses around the condition, and the braces are always required.

TypeScript
if (score > 90) {
console.log("A");
} else if (score > 70) {
console.log("B");
} else {
console.log("C");
}
Go
if score > 90 {
fmt.Println("A")
} else if score > 70 {
fmt.Println("B")
} else {
fmt.Println("C")
}

Go’s for covers every looping pattern:

TypeScript
// C-style
for (let i = 0; i < 5; i++) { ... }
// while
while (condition) { ... }
// infinite
while (true) { ... }
// for...of
for (const item of items) { ... }
Go
// C-style
for i := 0; i < 5; i++ { ... }
// while (drop init and post)
for condition { ... }
// infinite
for { ... }
// range (like for...of)
for i, item := range items { ... }

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.

TypeScript
switch (day) {
case "Mon":
case "Tue":
console.log("Weekday");
break; // required!
case "Sat":
case "Sun":
console.log("Weekend");
break;
default:
console.log("Unknown");
}
Go
switch day {
case "Mon", "Tue", "Wed", "Thu", "Fri":
fmt.Println("Weekday") // no break needed
case "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.

TypeScript
const nums = [10, 20, 30];
// index + value
nums.forEach((v, i) => console.log(i, v));
// value only
for (const v of nums) { console.log(v); }
Go
nums := []int{10, 20, 30}
// index + value
for i, v := range nums {
fmt.Println(i, v)
}
// value only (discard index)
for _, v := range nums {
fmt.Println(v)
}
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))
}
}
In Go, which keyword replaces while, do...while, and for...of?
Does Go switch fall through by default?
What does _ mean when used with range?
Which is valid Go — parentheses around the if condition?