2.3 Make Go Do Math: Operators & Type Conversion
TL;DR
- Operators are the action symbols like
+(add) and>(greater than). - Go is very strict about types. You can't add a whole number (
int) to a decimal number (float64) without telling it exactly what to do. - Type conversion is how you manually change data from one type to another, like turning
5into5.0. - Type inference is Go's cool trick for guessing a variable's type when you use
:=.
Why This Matters
Think of operators and types as the grammar of programming. You can't tell the computer to perform a calculation or make a decision without them. Learning these rules is the first real step to making your program do something useful instead of just holding data. Get this right, and you'll avoid tons of common bugs and frustrations.
Concepts in Plain English
Before we dive in, let's get a few key ideas straight. These are the building blocks for everything that follows.
- Operator: This is an "action" symbol. It tells the computer to do something, like add numbers or compare them. - Operators are like the buttons on a calculator (
+,-,×,÷). They perform an operation on the numbers you give them. - Type: This is the kind of data a variable holds. Is it a whole number? A number with a decimal? Text? A true/false value? - A type is like a specific container. You put drinks in a cup and soup in a bowl. Go gets upset if you try to pour soup into a paper cone—the types don't match.
- Type Conversion: This is the act of manually changing a value from one type to another compatible type. - It's like melting an ice cube (a solid) to get water (a liquid). You still have H₂O, but you've changed its form to use it differently.
- Type Inference: This is when Go automatically figures out a variable's type based on the value you give it. - It’s like a smart cashier. When you put a banana on the counter, they know it's a fruit and weigh it accordingly, without you having to say, "This is a fruit."
Here’s a quick reference table:
| Term | Simple Definition | Where It Shows Up |
| Operator | A symbol that performs an action. | a + b, x > y |
| Type | The category or kind of data. | int, float64, string |
| Type Conversion | Manually changing a variable's type. | float64(myInteger) |
| Type Inference | Go automatically guessing the type. | age := 30 |
Quick Setup
You don't need to install anything to try these examples! You can run all the code snippets directly in your browser using the official Go Playground. Just copy, paste, and hit "Run."
Do It Step-by-Step
Let's break this down into three parts: using operators, converting types, and letting Go infer types for us.
1. Use Basic Operators for Math and Comparisons
Your goal is to perform simple calculations and check if statements are true or false.
- Input:
ais 15,bis 5. - Input:
scoreis 95,passingScoreis 70.
Output:
Is score equal to passing score? false
Is score greater than passing score? true
Comparison Operators: Use these to compare two values. The result is always a bool (true or false).
package main
import "fmt"
func main() {
score := 95
passingScore := 70
// The result of a comparison is always true or false.
fmt.Println("Is score equal to passing score?", score == passingScore) // "is equal to"
fmt.Println("Is score greater than passing score?", score > passingScore) // "is greater than"
}
Output:
Sum: 20
Difference: 10
Product: 75
Quotient: 3
Arithmetic Operators: Use these for basic math.
package main
import "fmt"
func main() {
a := 15
b := 5
// Use operators to do math, just like on a calculator.
fmt.Println("Sum:", a + b) // Addition
fmt.Println("Difference:", a - b) // Subtraction
fmt.Println("Product:", a * b) // Multiplication
fmt.Println("Quotient:", a / b) // Division
}
Pro tip — The%(modulo) operator gives you the remainder of a division. It's fantastic for checking if a number is even or odd (number % 2 == 0).
Here's a table to help you keep them straight:
| Operator Type | Symbols | What It Does | Example | Result |
| Arithmetic | +, -, *, /, % | Performs calculations. | 10 / 4 | 2 (integer division!) |
| Comparison | ==, !=, <, >, <=, >= | Compares two values. | 10 > 4 | true |
2. Convert Between Types Explicitly
Your goal is to make incompatible types work together without causing a compiler error.
- Input:
oranges(int5),price(float642.75).
Output:
Total cost: 13.75
The Solution: Convert one of the types to match the other. The syntax is TypeName(value).
package main
import "fmt"
func main() {
oranges := 5 // This is an int
price := 2.75 // This is a float64
// We convert `oranges` (an int) into a float64 before multiplying.
// Now both values are of the same type: float64.
totalCost := float64(oranges) * price
fmt.Println("Total cost:", totalCost)
}
The Problem: Go won't let you mix different numeric types in an operation. This code will fail:
// This code will NOT run!
oranges := 5 // This is an int
price := 2.75 // This is a float64
totalCost := oranges * price // ERROR: invalid operation (mismatched types)
Warning — When you convert afloat64to anint, Go truncates the value (chops off the decimal part). It does not round. For example,int(9.99)becomes9.
3. Let Go Guess the Type with :=
Your goal is to write cleaner, shorter code by letting Go handle the type declaration for you.
- Input:
name := "Alice",age := 30.
Output:
Name: Alice, Type: string
Age: 30, Type: int
The Short Way (Inference): Use the := operator. Go looks at the value on the right and infers the type for the new variable on the left.
package main
import "fmt"
func main() {
// Go sees "Alice" is text and infers the type is string.
name := "Alice"
// Go sees 30 is a whole number and infers the type is int.
age := 30
fmt.Printf("Name: %s, Type: %T\n", name, name)
fmt.Printf("Age: %d, Type: %T\n", age, age)
}
The %T verb in Printf is a special trick to print the type of a variable.
The Long Way (Explicit): You declare the variable and its type first, then assign a value.
var name string = "Alice"
var age int = 30
Examples Section
Let's see these concepts in a couple of practical scenarios.
Example A: A Simple Sum
This example just adds two numbers. It shows type inference (:=) and a basic arithmetic operator (+).
package main
import "fmt"
func main() {
// We declare two variables using type inference.
// Go knows these are `int` because they are whole numbers.
firstNumber := 101
secondNumber := 250
// The '+' operator adds them together.
// The result is stored in a new variable, also an `int`.
sum := firstNumber + secondNumber
fmt.Println("The sum is:", sum) // Prints: The sum is: 351
}
Example B: Calculating an Average Score
Here, we need type conversion to get an accurate result. If we divide two integers, we'll lose the decimal part.
package main
import "fmt"
func main() {
// Imagine these scores came from three tests.
// They are all whole numbers, so they are `int`.
score1 := 88
score2 := 92
score3 := 79
numberOfScores := 3
// First, calculate the total sum. This is still an `int`.
totalSum := score1 + score2 + score3
// THE CRITICAL STEP:
// To get a decimal average, we MUST convert our numbers to floats
// *before* we divide. Otherwise, `259 / 3` would be `86`, not `86.333`.
average := float64(totalSum) / float64(numberOfScores)
fmt.Printf("Total Sum: %d\n", totalSum)
fmt.Printf("Average Score: %f\n", average) // %f is for floats
}
This flow can be visualized like this:
flowchart LR
B[Add Integer Scores] --> C{Get totalSum: int}
C --> D[Convert totalSum to float64]
D --> E[Convert numberOfScores to float64]
E --> F[Divide the two floats]
F --> G[Get average: float64]An ASCII diagram showing the process: Start -> Add integer scores -> Convert sum and count to floats -> Divide -> Get average -> End.
Common Pitfalls
- Mismatched Types: Trying to do math with an
intand afloat64is the most common error. Fix: Always convert one type to match the other (float64(myInt)). - Integer Division: Forgetting that
5 / 2is2in Go, not2.5. Fix: If you need a precise decimal answer, make sure at least one of the numbers in your division is a float (e.g.,5.0 / 2orfloat64(5) / float64(2)). - Confusing
=and:=: Using:=when you mean to update an existing variable with=. Remember,:=declares a new variable, while=assigns a new value to an existing one.
FAQ
1. Why is Go so strict about types?
For safety and speed. By forcing you to be explicit, Go prevents a whole class of bugs where you might accidentally add a number to a piece of text. It also makes the program run faster because the computer knows exactly what kind of data it's dealing with.
2. What’s the difference between = and := again?
= is the assignment operator. It gives a new value to a variable that already exists.
:= is the short declaration operator. It both declares a new variable and gives it an initial value, inferring the type automatically.
3. Can I convert a string like "123" to a number?
Yes, but not by just writing int("123"). You need to use a special helper function from Go's strconv (string conversion) package, like strconv.Atoi. That's a topic for another day!
4. When should I declare a type explicitly instead of using :=?
You should be explicit when you want to declare a variable but aren't ready to assign its value yet, or when you want a variable to have a specific type that Go might not guess. For example, var totalScore float64 ensures totalScore starts as 0.0 and can hold decimals later.
Recap
You've learned the fundamental rules for making Go compute things. Stick to these, and you'll be in great shape.
- Use operators (
+,-,*,/,==,>) to do math and make comparisons. - Always remember that Go requires types to match. No mixing
intandfloat64! - Use type conversion (
TypeName(value)) to make different types compatible. - Use type inference (
:=) to write clean, concise code inside your functions. - Next step: Try writing a tiny program that asks for two numbers and prints their sum, difference, product, and a properly calculated quotient.