Lesson 2 · Unit 01
Variables and types
Names for values, the four basic types, and converting between them on purpose.
What you practise
varand:=,int,float64,stringandbool, zero values, constants, converting between types on purpose, the unused variable the compiler refuses
Try a question from this lesson
Pick one
The first line gives the number 3 a name. After that, the name can stand in for the number. What does this print?
apples := 3
fmt.Println(apples + 2)Correct answer
5
Why
Go looks up the name apples, finds 3, and adds 2. A name without quote marks is never printed as text: Go always replaces it with the value it holds.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Variables
A variable is a name for a value. score := 10 creates the variable score and puts 10 in it. From then on, writing score means "whatever is in there now".
A variable can be given a new value with a plain =. The old value is gone. So := creates a variable, and = changes one that already exists.
score := 10 // create it
fmt.Println(score) // 10
score = 25 // change it
fmt.Println(score) // 25Concept
Every value has a type
Go sorts values into types, and a variable keeps the type of its first value for good.
int is a whole number. float64 is a number with a decimal point. string is text. bool is one of two values, true or false, for yes-or-no facts.
The type decides what you can do with a value: you can multiply two numbers, but not two strings.
age := 30 // int
price := 2.5 // float64
name := "Ada" // string
ready := true // bool
fmt.Println(age, price, name, ready)Concept
var, zero values and const
There is a longer way to create a variable: var total int. You name the type, and Go fills in a starting value, the zero value: 0 for numbers, "" (empty text) for strings, false for bools.
Use := when you have a value ready, and var when you do not have one yet.
const creates a name whose value can never change.
var total int // starts at 0
var done bool // starts at false
const perBox = 12 // fixed for good
total = total + perBox
fmt.Println(total, done) // 12 false9 more exercises in the app
- 3× type the answer
- 1× fill the blanks
- 1× match the pairs
- 2× multiple choice
- 1× order the lines
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.