The Building Blocks
The Building Blocks
Every value in Go has a type. These four cover most of what you'll write:
| Type | What it holds | Example |
|---|---|---|
int |
Integers | 42, -7, 0 |
float64 |
Decimals | 3.14, 0.5 |
string |
Text (in quotes) | "hello", "Go" |
bool |
True or false | true, false |
You can do math with numbers, compare them, and glue strings together:
example.go
fmt.Println(10 + 3) // 13
fmt.Println(10 > 3) // true
fmt.Println("Go" + "lang") // Golang
fmt.Println(7.0 / 2.0) // 3.5
Comparisons (>, <, >=, <=, ==, !=) always produce a bool. The + operator adds numbers or joins strings.
Spaces when printing multiple values
fmt.Println inserts a space between each argument. + joins strings with nothing between them. If your string already ends in a space and you then use a comma, you get two spaces:
example.go
fmt.Println("a", "b") // a b
fmt.Println("a" + "b") // ab
fmt.Println("Status: ", "OK") // Status: OK (two spaces)
fmt.Println("Status: " + "OK") // Status: OK (one space)
Two Things Go Won't Let You Do
- Mixing types. You can't add an
intto afloat64, or a number to astring. The compiler catches it before your code runs. - Unused variables. Every declared variable must be used, or the compiler stops with an error like
declared and not used.
>_Exercise
Exercise: Health Check
You're building an API health endpoint. Fill in the three fmt.Println calls so the output matches:
example.go
Status: OK
Healthy: true
Latency: 1.5Each line uses a different technique:
- Status - join two strings with
+ - Healthy - use
==to comparestatusCodeto200(this produces abool) - Latency - divide two floats to get
1.5
Stuck? Reveal a hint to help you.
Hints (0/4)
Key Takeaway
Next UpStoring values so you can use them later.