Numbers and Strings
Doing math and handling text
Almost every program works with numbers, text, or both. Go gives each its own types, and it is picky about keeping them separate, which saves you from a whole family of sneaky bugs.
Two number types to start with
intholds whole numbers:-3,0,42float64holds numbers with a decimal point:3.14,-0.5
The usual math operators work on both:
fmt.Println(8 + 3)
fmt.Println(8 - 3)
fmt.Println(8 * 3)
fmt.Println(8 / 3)
fmt.Println(8 % 3)Those print 11, 5, 24, 2, and 2. Wait, why does 8 / 3 print 2 and not 2.66? Because both numbers are ints, Go does whole number division and throws away the remainder. The % operator gives you that remainder: 8 divided by 3 is 2, remainder 2.
fmt.Println(8.0 / 3.0)With float64 values, division keeps the decimals and prints 2.6666666666666665.
Mixing types needs a conversion
Go will not silently mix an int with a float64. You convert one of them on purpose:
slices := 8
people := 3
each := float64(slices) / float64(people)
fmt.Println(each)float64(slices) makes a float copy of the int. Explicit conversions feel wordy at first, but they mean you always know exactly what your numbers are doing.
Strings
A string is text inside double quotes. You can glue strings together with + and measure them with len:
first := "Grace"
last := "Hopper"
full := first + " " + last
fmt.Println(full)
fmt.Println(len(full))That prints Grace Hopper and then 12, counting the space too.
You cannot use + between a string and a number. The easy fix while you learn: pass them to Println as separate values with commas, and let it do the mixing for you. Later, fmt.Sprintf will build fancy strings from templates.
Quick check
Q1 In Go, what is 7 / 2 when both numbers are ints?
Q2 What does the % operator do with whole numbers?
Want to save your progress? It's free.
Create a free account