Lesson 4 of 20 · Part 1: Getting started
Numbers, strings and booleans
Go basic types for beginners. Integers, floats, strings, runes and booleans, type conversion with strconv, and formatted printing with fmt.Printf verbs.
7 min read · Updated · Beginner friendly
What you'll learn
- Choose between int, float64 and the other number types
- Work with strings, bytes and runes (and why len can surprise you)
- Combine conditions with boolean operators
- Convert between types and format output with Printf
Every value in Go has a type. The type decides what the value can hold and what you can do with it. This lesson covers the basic types you will use in almost every program: numbers, strings and booleans.
Integers
Integers are whole numbers, such as -3, 0 and 42. Go has several integer types that differ in size:
| Type | Size | Range |
|---|---|---|
int8 |
8 bits | -128 to 127 |
int16 |
16 bits | -32,768 to 32,767 |
int32 |
32 bits | about ±2.1 billion |
int64 |
64 bits | about ±9.2 quintillion |
int |
32 or 64 bits | 64 bits on all modern computers |
uint8 … uint64, uint |
same sizes | 0 and up only (“unsigned”) |
There are two handy aliases: byte is the same as uint8, and rune is the same as int32 (used for characters, as you will see below).
Which one should I use?
Use int unless you have a specific reason not to. The sized types are for special cases such as binary file formats or saving memory in very large arrays.
Arithmetic
package main
import "fmt"
func main() {
a, b := 17, 5
fmt.Println("a + b =", a+b)
fmt.Println("a - b =", a-b)
fmt.Println("a * b =", a*b)
fmt.Println("a / b =", a/b) // integer division drops the remainder
fmt.Println("a % b =", a%b) // % gives the remainder
}a + b = 22
a - b = 12
a * b = 85
a / b = 3
a % b = 2Dividing two integers gives an integer, so 17 / 5 is 3, not 3.4. The remainder operator % is very useful: n % 2 == 0 checks whether a number is even, and n % 10 gives its last digit.
Go also has shortcuts for updating a variable:
package main
import "fmt"
func main() {
score := 10
score += 5 // same as score = score + 5
score *= 2 // same as score = score * 2
score-- // subtract one
score++ // add one
fmt.Println(score)
}30++ and -- are statements in Go, not expressions, so you can’t write x = y++. This removes a common source of confusing code.
Overflow
Each integer type has a maximum value. If a calculation goes past it, the number wraps around:
package main
import "fmt"
func main() {
var small int8 = 127
small++
fmt.Println(small)
}-128With int (64 bits) you are very unlikely to hit the limit in everyday code, which is another reason to prefer it.
Floating-point numbers
Numbers with a decimal point are floats. Go has float32 and float64; use float64, which is the default when you write 3.14.
package main
import (
"fmt"
"math"
)
func main() {
price := 19.99
quantity := 3.0
fmt.Println("total:", price*quantity)
fmt.Println("square root of 2:", math.Sqrt(2))
fmt.Println("rounded:", math.Round(2.5), "floor:", math.Floor(2.7), "ceil:", math.Ceil(2.1))
a, b := 0.1, 0.2
fmt.Println("tiny surprise:", a+b)
}total: 59.97
square root of 2: 1.4142135623730951
rounded: 3 floor: 2 ceil: 3
tiny surprise: 0.30000000000000004The last line is not a Go bug. Computers store floats in binary, and some decimal numbers like 0.1 can’t be stored exactly. This happens in nearly every programming language.
(If you write fmt.Println(0.1 + 0.2) with the numbers typed directly, Go prints 0.3. Constants are calculated exactly by the compiler; the rounding only appears once the values are stored in float64 variables.)
Money and floats
Because of these tiny rounding errors, don’t use floats for money in real applications. A common approach is to store amounts as whole numbers of the smallest unit, such as cents or paise, in an int.
Strings
A string is a sequence of text. You write it in double quotes:
package main
import "fmt"
func main() {
first := "Hello"
second := "Gopher"
greeting := first + ", " + second + "!" // + joins strings
fmt.Println(greeting)
fmt.Println("length:", len(greeting))
fmt.Println("first byte:", greeting[0]) // a number (the byte value)
fmt.Println("first letter:", string(greeting[0])) // convert it back to text
fmt.Println("a slice of it:", greeting[7:13])
}Hello, Gopher!
length: 14
first byte: 72
first letter: H
a slice of it: GopherA few things to know:
greeting[i]gives you a byte (a number), not a one-letter string.greeting[7:13]takes a slice from index 7 up to, but not including, index 13.- Strings are immutable: you can’t change a character in place. You build a new string instead.
Escape sequences and raw strings
Inside double quotes, a backslash starts an escape sequence: \n is a new line, \t is a tab, \" is a quote and \\ is a backslash.
For text with many backslashes or several lines, use a raw string with backticks. Everything between the backticks is taken literally:
package main
import "fmt"
func main() {
fmt.Println("Name:\tGopher\nSays:\t\"hi\"")
path := `C:\Users\gopher\notes.txt`
poem := `Roses are red,
Gophers are blue.`
fmt.Println(path)
fmt.Println(poem)
}Name: Gopher
Says: "hi"
C:\Users\gopher\notes.txt
Roses are red,
Gophers are blue.Bytes, runes and Unicode
Go strings are stored as UTF-8. English letters take one byte each, but many characters, such as é, ₹ or emoji, take two to four bytes. len counts bytes, not characters:
package main
import (
"fmt"
"unicode/utf8"
)
func main() {
word := "café"
fmt.Println("bytes:", len(word))
fmt.Println("characters:", utf8.RuneCountInString(word))
for i, r := range word {
fmt.Printf("index %d: %c\n", i, r)
}
}bytes: 5
characters: 4
index 0: c
index 1: a
index 2: f
index 3: éA single character (a Unicode code point) is called a rune. You write a rune with single quotes: 'é'. Looping over a string with for ... range gives you runes, which is the safe way to go through text character by character. Notice that é starts at index 3 and uses two bytes.
The strings package
The standard library’s strings package has dozens of helpers. Here are some you will use often:
package main
import (
"fmt"
"strings"
)
func main() {
s := " Go is simple, Go is fast "
clean := strings.TrimSpace(s)
fmt.Println(clean)
fmt.Println(strings.ToUpper(clean))
fmt.Println(strings.Contains(clean, "fast"))
fmt.Println(strings.Count(clean, "Go"))
fmt.Println(strings.ReplaceAll(clean, "Go", "Gopher"))
fmt.Println(strings.Split("red,green,blue", ","))
fmt.Println(strings.Join([]string{"a", "b", "c"}, "-"))
fmt.Println(strings.Repeat("=", 10))
}Go is simple, Go is fast
GO IS SIMPLE, GO IS FAST
true
2
Gopher is simple, Gopher is fast
[red green blue]
a-b-c
==========Booleans
A bool is either true or false. Comparisons produce booleans, and you combine them with logical operators:
| Operator | Meaning | Example |
|---|---|---|
==, != |
equal, not equal | age == 18 |
<, <=, >, >= |
comparisons | score >= 50 |
&& |
and: both must be true | age >= 18 && hasTicket |
|| |
or: at least one is true | isAdmin || isOwner |
! |
not: flips the value | !loggedIn |
package main
import "fmt"
func main() {
age := 20
hasTicket := true
canEnter := age >= 18 && hasTicket
isTeen := age >= 13 && age <= 19
fmt.Println("can enter:", canEnter)
fmt.Println("is a teenager:", isTeen)
fmt.Println("not a teenager:", !isTeen)
}can enter: true
is a teenager: false
not a teenager: true&& and || short-circuit: if the left side already decides the answer, the right side is not evaluated. For example, in false && expensiveCheck(), the function is never called.
Type conversion
Go never converts between types automatically, even between int and float64. Mixing them is a compile error:
package main
import "fmt"
func main() {
count := 3
price := 2.5
fmt.Println(price * count)
}invalid operation: price * count (mismatched types float64 and int)You convert explicitly by writing the type name like a function, T(value):
package main
import "fmt"
func main() {
count := 3
price := 2.5
total := price * float64(count)
fmt.Println("total:", total)
rating := 4.8
fmt.Println("as int:", int(rating)) // drops the decimal part, no rounding
}total: 7.5
as int: 4Converting between numbers and strings
To turn a number into text or text into a number, use the strconv (“string conversion”) package:
package main
import (
"fmt"
"strconv"
)
func main() {
n := 42
s := strconv.Itoa(n) // int to string ("Integer to ASCII")
fmt.Println("as text: " + s)
age, err := strconv.Atoi("27") // string to int
fmt.Println(age+1, err)
_, err = strconv.Atoi("twenty")
fmt.Println("error:", err)
f, _ := strconv.ParseFloat("3.75", 64)
fmt.Println(f * 2)
}as text: 42
28 <nil>
error: strconv.Atoi: parsing "twenty": invalid syntax
7.5strconv.Atoi returns two values: the number and an error. When the conversion works, the error is nil (no error). Checking errors like this is everyday Go, and lesson 11 is all about it.
string(65) is not "65"
Writing string(65) gives you "A", the character with code 65, not the text "65". To turn a number into its digits, always use strconv.Itoa or fmt.Sprint. The go vet tool warns you about this mistake.
Printing with fmt.Printf
fmt.Printf uses verbs, placeholders starting with %, to format values. The ones you’ll use most:
| Verb | Prints | Example output |
|---|---|---|
%v |
any value in a default format | 42, [1 2 3] |
%T |
the type of a value | float64 |
%d |
an integer | 42 |
%f, %.2f |
a float, with 2 decimals | 3.141593, 3.14 |
%s |
a string | Go |
%q |
a quoted string | "Go" |
%t |
a bool | true |
%c |
a rune as a character | é |
%5d, %-8s |
pad to a width (right / left aligned) | 42, Go |
package main
import "fmt"
func main() {
name := "Gopher"
pi := 3.14159265
year := 2009
fmt.Printf("%v | %v | %v\n", name, pi, year)
fmt.Printf("%T | %T | %T\n", name, pi, year)
fmt.Printf("%q has %d letters\n", name, len(name))
fmt.Printf("pi is about %.2f\n", pi)
// Aligned columns
fmt.Printf("%-10s %8s\n", "Item", "Price")
fmt.Printf("%-10s %8.2f\n", "Coffee", 3.5)
fmt.Printf("%-10s %8.2f\n", "Sandwich", 12.25)
}Gopher | 3.14159265 | 2009
string | float64 | int
"Gopher" has 6 letters
pi is about 3.14
Item Price
Coffee 3.50
Sandwich 12.25fmt.Sprintf works exactly like Printf, but returns the formatted string instead of printing it: label := fmt.Sprintf("%d items", 3).
Exercises
1. Temperature converter. Convert 36.6 degrees Celsius to Fahrenheit using F = C × 9 / 5 + 32 and print it with one decimal place.
Show solution
package main
import "fmt"
func main() {
celsius := 36.6
fahrenheit := celsius*9/5 + 32
fmt.Printf("%.1f°C is %.1f°F\n", celsius, fahrenheit)
}36.6°C is 97.9°F2. Seconds to time. Given total := 7384 seconds, print it as hours, minutes and seconds using / and %.
Show solution
package main
import "fmt"
func main() {
total := 7384
hours := total / 3600
minutes := total % 3600 / 60
seconds := total % 60
fmt.Printf("%d seconds = %dh %dm %ds\n", total, hours, minutes, seconds)
}7384 seconds = 2h 3m 4s3. Count the characters. For the string "नमस्ते Go", print the number of bytes and the number of runes. Why are they different?
Show solution
package main
import (
"fmt"
"unicode/utf8"
)
func main() {
s := "नमस्ते Go"
fmt.Println("bytes:", len(s))
fmt.Println("runes:", utf8.RuneCountInString(s))
}bytes: 21
runes: 9Each Devanagari character takes 3 bytes in UTF-8, while the space, G and o take one byte each. len counts bytes; utf8.RuneCountInString counts code points.
4. Add two numbers from text. You receive "12" and "30" as strings. Convert them, add them, and print 12 + 30 = 42.
Show solution
package main
import (
"fmt"
"strconv"
)
func main() {
a, errA := strconv.Atoi("12")
b, errB := strconv.Atoi("30")
if errA != nil || errB != nil {
fmt.Println("not a number")
return
}
fmt.Printf("%d + %d = %d\n", a, b, a+b)
}12 + 30 = 42Recap
- Use
intfor whole numbers andfloat64for decimals; integer division drops the remainder. - Strings are immutable UTF-8 text;
lencounts bytes, andrangegives runes. - Booleans combine with
&&,||and!. - Go never converts types for you: use
T(value)for numbers andstrconvfor text. fmt.Printfverbs such as%d,%.2f,%s,%vand%Tcontrol formatting.
Next, you will make decisions and repeat work with if, for and switch.
Finished this lesson?
Your progress is saved in this browser only.