Variables 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.
Try it
- Go vs JavaScript – Pick an idea (variable, loop, list, error...) and see the JavaScript and the Go side by side.
- Go type checker – Pick a type and a value and see whether Go would accept it, with the compiler's own message.
Transcript
A variable is a named box. In Go, the box also has a type, and the type is fixed when you make it. An int holds whole numbers, a float sixty four holds decimals, a string holds text, and a bool holds true or false.
You make a variable with var, a name and a type. Or use the short form, colon equals, and Go works out the type from the value.
The type cannot change. If score is an int, you cannot put the text ten in it. The compiler stops you before the program runs. In JavaScript, nothing would complain until much later.
If you do not give a variable a value, it gets a zero value: zero for numbers, an empty string for text, and false for a bool.
Remember: a Go variable has a type that is fixed. Use var, or colon equals for the short form. Int, float sixty four, string and bool are the first four types.
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:1934If, 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.
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.