Basic Types
Every variable has a type. The type decides what kind of value the variable can hold, and what you can do with it. These four types are enough for a long time:
| Type | Holds | Example |
|---|---|---|
int | whole numbers | 3, -12, 0 |
float64 | numbers with a decimal part | 12.5, -0.25 |
string | text, in double quotes | "Alice" |
bool | true or false | true |
package main
import "fmt"
func main() {
var name string = "Alice"
var packages int = 3
var distance float64 = 12.5
var priority bool = true
fmt.Println(name, packages, distance, priority)
}
Output:
Alice 3 12.5 true
The name float64 comes from "floating point", the way computers store decimal numbers. The 64 is its size: it uses 64 bits, the smallest units of computer memory. A bool (short for "boolean") has only two values, true and false. You will use them a lot to make decisions in the next section.
Zero values
A variable declared without a value gets the zero value of its type. For numbers it is 0, for a string it is "" (the empty string), and for a bool it is false:
var count int
var price float64
var name string
var done bool
fmt.Println(count, price, name, done)
Output:
0 0 false
The empty string prints as nothing, which is why you see two spaces before false. In Go, a variable always has a known value. It never holds leftover data from memory.
How a float64 prints
Println prints a float64 in its shortest form:
a := 3.0
b := 12.50
c := 1500000.0
fmt.Println(a, b, c)
Output:
3 12.5 1.5e+06
3.0 printed as 3, and 12.50 lost its last zero. The big number printed in a short form: 1.5e+06 means 1.5 times 1,000,000. The Formatted Output lesson shows how to choose the digits yourself.
A float64 is also not always exact:
x := 0.1
y := 0.2
fmt.Println(x + y)
Output:
0.30000000000000004
Computers store these numbers in binary, and 0.1 has no exact binary form, just like 1/3 has no exact decimal form. The tiny error shows up in the result. This is why programs that work with money often count whole cents in an int.
Other number types
Go also has number types with a size in their name, like int8, int32 and int64. An int8 uses 8 bits and holds only -128 to 127. Plain int is the right choice for almost every whole number, and the Math Functions lesson shows how big it can get.
A value must fit its type
Go checks every value against the type of its variable. A decimal number cannot go into an int:
package main
import "fmt"
func main() {
var count int = 2.5
fmt.Println(count)
}
Output:
# command-line-arguments
./main.go:6:18: cannot use 2.5 (untyped float constant) as int value in variable declaration (truncated)
"Truncated" means the .5 would be cut off. Go will not lose part of a value without you asking, so it stops with an error.
In the exercise, give four delivery variables the right types.