If, for and switch
Decisions and loops in Go: if and else without brackets, the three shapes of for (counted, condition, forever), and switch, next to the same ideas in Scratch.
Try it
- Go vs JavaScript – Pick an idea (variable, loop, list, error...) and see the JavaScript and the Go side by side.
Transcript
Decisions look familiar. An if checks a condition, and else handles the other case. In Go you do not put brackets around the condition, but the curly braces are always required.
Go has only one loop: for. It has three shapes. A counted loop with a start, a test and a step. A loop with just a test, like a while loop in other languages. And a loop that goes on forever, until you break out of it.
A switch picks one case. It is a tidy way to write many if and else checks, and Go stops at the first case that matches.
Compare with Scratch. Repeat ten is a for loop. The if and else blocks are if and else. The same road signs, written as text.
Remember: if and else decide, for is the only loop with three shapes, and switch picks one case.
More in this series
1:3832What is Go?
Go is a compiled language: the compiler turns main.go into a program and checks it before it runs. go run, go build, and the three parts of a first program.
1:2633Variables and types
In Go every variable has a fixed type: int, float64, string or bool. var and :=, why the compiler rejects the wrong type, and zero values.
1:2035Slices and maps
A slice is a growing list of one type (append, len, range) and a map connects keys to values (delete, and the comma ok check).
1:1736Structs and methods
A struct groups named, typed fields into your own type, a method is a function that belongs to a type, and a pointer receiver changes the real value instead of a copy.
1:1637Errors in Go
A function that can fail returns an error as a second value. nil means success, and you check it with if err != nil, instead of an error jumping out like in JavaScript.
1:1838Testing in Go
A test is a small program that checks your code. _test.go files, Test functions, go test with PASS and FAIL, and table tests with many cases.
1:2139Packages and modules
A package is a folder of Go files, a module is the whole project (go mod init, go.mod), how import works, and why a capital letter makes a name visible.