Lesson 1 · Unit 01
Values and functions
Declarations, zero values, strict types, several results, one loop.
What you practise
varand:=, zero values, basic types and conversions, constants, functions with several return values,ifandforas the only loop
Try a question from this lesson
Pick one
In Python a name does not exist until you assign it. This Go program declares three variables without a value. What prints?
var n int
var s string
var ok bool
fmt.Println(n, s == "", ok)Correct answer
0 true false
Why
Every Go type has a zero value, and var gives it to you: 0 for an int, the empty string for a string, false for a bool. Nothing is nil here and nothing is uninitialised, so the program compiles and each variable is safe to read.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Declared means usable
var n int declares a variable and gives it the zero value of its type: 0 for numbers, "" for strings, false for bools. There is no None for these types.
Inside a function, x := 5 declares and assigns in one step, and the type comes from the value. Plain = assigns to a variable that already exists. The type of a variable never changes.
var count int // starts at 0
name := "gopher" // a string, for good
count = count + 1
fmt.Println(count, name) // 1 gopherConcept
Functions return several values
Types come after names: a, b int are two int parameters, and the result types follow the parameter list. A function can return more than one value, and the caller receives them all with :=. You will meet this shape constantly: a result plus an ok flag, or a result plus an error.
if takes no parentheses around its condition and always needs braces. Use _ for a result you do not want.
func minMax(a, b int) (int, int) {
if a < b {
return a, b
}
return b, a
}
lo, hi := minMax(9, 4)
fmt.Println(lo, hi) // 4 910 more exercises in the app
- 1× fill the blanks
- 2× multiple choice
- 4× type the answer
- 1× true or false
- 1× order the lines
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.