Lesson 4 of 38 · Fundamentals
Go Constants and Arithmetic Operators
Games run on numbers: damage, gold, cooldowns, experience points. In this lesson you will give fixed values a name with constants, calculate with Go's arithmetic operators, and use the math package when you need square roots, powers or rounding.
Constants
A constant is a name for a value that never changes. Declare it with const instead of var:
const maxLevel = 50
const realmName = "The Gopher Isles"
The value is fixed when the program is compiled, so maxLevel = 60 is a compile error. Constants hold numbers, strings and booleans, and their value must be known at compile time: const root = math.Sqrt(2) fails, because a function only runs when the program runs.
Group related constants in a block and build them from each other:
const (
secondsPerMinute = 60
secondsPerHour = 60 * secondsPerMinute // 3600
)
A name like secondsPerHour explains what 3600 means, and if a value ever changes, you edit it in one place. Unlike variables, unused constants are not an error.
Typed and untyped constants
const bonus = 10 is an untyped constant: it has no fixed type yet, so Go gives it whatever numeric type the expression around it needs. Give a constant a type, and it follows the same strict rules as a variable:
const bonus = 10 // untyped
const typedBonus int = 10 // an int
gold := 2.5
fmt.Println(gold + bonus) // 12.5
// gold + typedBonus fails: mismatched types float64 and int
That flexibility is why math.Pi, an untyped constant, can be multiplied with any float64. Prefer untyped constants unless you need a specific type.
iota: numbered constants
Inside a const block, iota starts at 0 and grows by one on each line. When you leave out a value, the previous expression is repeated:
const (
common = iota // 0
rare // 1
epic // 2
)
This is how Go creates enumerations — a set of related, numbered names. Write iota + 1 to start counting at 1.
Arithmetic operators
Go has +, -, * and /, plus % for the remainder. When both operands are integers, / performs integer division: the fraction is dropped (truncated toward zero). With a floating-point operand you get the exact result:
package main
import "fmt"
func main() {
fmt.Println(17/5, 17%5)
fmt.Println(-17/5, -17%5)
fmt.Println(17.0 / 5)
}
3 2
-3 -2
3.4
The remainder takes the sign of the left operand, so -17 % 5 is -2. Integer division and % work as a team: total / 60 gives whole minutes, total % 60 the seconds left over, and n%2 == 0 tells you whether n is even. A comparison such as == or >= produces a bool. The + operator also joins strings: "Go" + "pher" is "Gopher".
Shortcuts: +=, ++ and --
Updating a variable based on its own value is so common that Go has shortcuts:
score := 10
score += 5 // same as score = score + 5 → 15
score *= 2 // 30
score /= 4 // 7 (integer division)
score %= 4 // 3
score++ // 4
score-- // 3
In Go, ++ and -- are statements, not expressions: total := count++ and ++count don't compile. Put them on their own line.
Operator precedence
*, / and % bind tighter than + and -; operators of the same precedence are applied left to right. Use parentheses for a different order — or just to make your intent obvious:
fmt.Println(2 + 3*4) // 14
fmt.Println((2 + 3) * 4) // 20
fmt.Println(7 / 2 * 2) // 6, because 7 / 2 is 3
The math package
The standard math package provides functions and constants for floating-point math. To import it next to fmt, use a grouped import:
package main
import (
"fmt"
"math"
)
func main() {
fmt.Println(math.Sqrt(16), math.Pow(2, 10))
fmt.Println(math.Abs(-7.5), math.Round(2.5))
fmt.Println(math.Pi)
fmt.Println(math.Round(3.14159*100) / 100)
}
4 1024
7.5 3
3.141592653589793
3.14
These functions take and return float64, so convert integers first: math.Sqrt(float64(n)). math.Round rounds halves away from zero. The last line shows a handy trick for rounding to two decimals: multiply by 100, round, divide by 100.
Common mistakes
- Integer division:
7 / 2is3. Convert tofloat64first if you need3.5. - Testing for odd numbers with
n%2 == 1: for negativenthe remainder is-1. Usen%2 != 0. - Using
^as a power operator: in Go it is bitwise XOR, so2^3is1. Usemath.Pow(2, 3). - Passing an
inttomathfunctions:math.Sqrt(n)fails withcannot use n (variable of type int) as float64 value.
Assignment
The function skeletons are given — put your code where the TODO comments are and use return to hand back the result.
ToSeconds(hours, minutes, seconds int) intconverts a duration to seconds. Declare the constantssecondsPerMinuteandsecondsPerHourand use them.ToSeconds(1, 1, 1)is3661.CircleArea(r float64) float64returns the area of a circle with radiusr(π·r²) usingmath.Pi.CircleArea(2)is about12.566.IsEven(n int) boolreports whethernis even. It must also work for zero and negative numbers:IsEven(-4)istrue,IsEven(-3)isfalse.RoundTo2(x float64) float64roundsxto two decimal places:RoundTo2(3.14159)is3.14andRoundTo2(-1.236)is-1.24.
Numbers and math operators in other languages
- JavaScript Numbers and Math Operators · JavaScript
- Python Numbers and Arithmetic Operators · Python
- Java Operators: Integer vs Double Math · Java
- C# Operators: Arithmetic, Comparison and Logic · C#
Need a quick reminder? The Go cheat sheet has every topic of Learn Go on one page.
Lesson last updated on .