Variables and types

Knowledge Videos

Short animated explainers, organised by subject.

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

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