Introduction
A program has to remember things: a score, a name, a price. A variable is a named place that holds a value. Go is a statically typed language, which means that every variable has one type that is fixed when the program is compiled. The compiler uses the types to find mistakes early, for example if you try to add a number to a word. This lesson shows how to create variables, which types to use, how to convert between them, and how to name values that never change.
How it works
There are two ways to declare a variable. The long form uses var:
var count int = 7
var price float64 = 2.5
var total int
The last line gives no value, so total has the zero value of its type: 0 for numbers, "" (empty text) for strings and false for booleans. The short form := declares a variable and gives it a value, and Go works out the type from the value:
name := "Go"
ok := true
:= can only be used inside a function. Use = to give a new value to a variable that already exists. Declaring a variable and never using it is a compile error.
The most common types are int for whole numbers, float64 for decimal numbers, string for text, and bool for true or false. Other whole number types are int64 (a very large range), uint8 (0 to 255, also called byte) and rune for one character, written with single quotes such as 'G'. On this site int has 32 bits, so it holds values up to 2147483647; on most computers it has 64 bits. When a number can grow large, use int64. When a number goes past the range of its type, it wraps around: a uint8 holding 250 plus 10 becomes 4.
Go never converts numbers between types by itself. You must write the conversion: float64(count) turns an int into a float64, and int(price) cuts off the decimals. Dividing two ints gives an int, so 7 / 2 is 3; % gives the remainder, so 7 % 2 is 1.
A constant is declared with const. Its value is fixed and cannot change. Constants can be grouped in brackets, and a constant without a type, such as const Pi = 3.14159, adapts to the place where it is used.
Example
package main
import "fmt"
const Pi = 3.14159
const (
Small = 1
Big = Small * 1000
)
func main() {
var count int = 7
var price float64 = 2.5
name := "Go"
ok := true
var empty int
var text string
fmt.Println(count, price, name, ok)
fmt.Println(empty, text == "", Big)
total := float64(count) * price
fmt.Println("total:", total)
fmt.Println(7/2, 7%2, 7.0/2)
var big int64 = 3000000000
fmt.Println(big * 2)
var small uint8 = 250
small += 10
fmt.Println(small)
r := 'G'
fmt.Println(r, string(r))
fmt.Printf("%T %T %T %T\n", count, price, name, ok)
fmt.Println(Pi)
}Line by line
const Piand the groupSmallandBigdefine constants;Bigis calculated fromSmall.var count int = 7uses the long form, andname := "Go"uses the short form.var empty intandvar text stringshow zero values:0and an empty string.float64(count) * priceconverts first, because Go does not mix int and float64.7/2gives 3 and7%2gives 1, but7.0/2is a decimal division and gives 3.5.big * 2works becausebigis an int64.small += 10wraps a uint8 around.- A rune is a number:
'G'prints as 71, andstring(r)turns it back into text.%Tprints the type.
Expected result
7 2.5 Go true
0 true 1000
total: 17.5
3 1 3.5
6000000000
4
71 G
int float64 string bool
3.14159
In the real world
Choosing types is part of designing real software. Money is often stored as a whole number of cents in an int64 to avoid rounding errors, ids use int64, and measurements use float64. Because Go checks types at compile time, a whole class of bugs, such as adding a price to a name, cannot reach production.
Common mistakes
- Mixing int and float64 in one calculation. Convert one of them first.
- Using := outside a function, or using := twice for the same name in the same place.
- Declaring a variable and never using it, which the compiler rejects.
- Forgetting that 7 / 2 is 3 when both numbers are ints.
- Overflowing int with large values; use int64 when numbers can pass two billion.
Best practices
- Use
:=inside functions andvarwhen you want the zero value. - Give variables clear names such as
totalPrice, written in camelCase. - Use constants for fixed numbers instead of repeating them in the code.
Summary
Variables are declared with var or :=, and every one has a type and a zero value. The common types are int, int64, float64, string, bool and rune. Go converts between number types only when you ask, with float64(x) or int(y), and const gives names to fixed values.
Quick check
Key takeaways
- Use := inside functions to declare and set a variable in one step; Go works out the type.
- Go never converts between number types by itself: write float64(x) or int(y).
- Every variable has a zero value; constants are fixed values given with const.
Practice problems for this lesson
Was this lesson clear?
My notes
Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.