GO
Your First Go Program: Splitting a Carpool's Fuel Bill Without Losing Cents
Introduction
Go is often described as a simple language, and in one sense it is: there are few keywords and few ways to write the same thing. But the first hour with Go surprises almost everyone, because the compiler refuses code that other languages accept. An unused variable stops the build. So does an unused import. So does dividing a decimal number by a whole number. Each of these rules exists for a reason, and once you know the reason, the error messages turn from obstacles into help.
In this tutorial we will write a small program that splits a month of fuel costs between the people in a carpool. We will run it with go run, build it with go build, and break it on purpose to read Go's compiler errors. Along the way we will find out where integer division quietly loses money, why Go makes you convert between int and float64 yourself, and how go vet catches a formatting mistake the compiler lets through.
I will assume you are working in the Go sandbox on Bytestark. Your terminal starts in /home/coder/learning, which already holds a Go module named learning (that is what the go.mod file there declares). We will create a folder for our program inside it. You do not need to know any Go yet.
Background
Go is a compiled language. The .go files you write are source code; the go tool turns them into an executable, a file of machine instructions that runs directly on the processor. You use the same tool for everything: go run compiles and runs in one step, go build compiles and leaves the executable on disk, and go vet looks for suspicious code.
Go code is organised in packages. Every .go file starts with a package line, and all files in one folder belong to the same package. A package named main is special: it is the one that becomes a program, and its function main is where the program starts. Other packages are libraries that programs use. fmt, which we will use for printing, is a package from Go's standard library, and you bring it in with an import line.
Every value in Go has a type. Two matter here. int holds whole numbers like 4 or 11143. float64 holds numbers with a fractional part, like 0.27. Go never converts between them silently, which is the source of several errors in this tutorial and of several bugs it prevents.
Finally, Go has a short way to create a variable: people := 4 declares a new variable named people, works out its type from the value (here int), and stores the value. The := only works for new names; to change an existing variable you use plain =.
Practical Scenario
Four colleagues, Ana, Bogdan, Carla and Dan, drive to work together in Ana's car. At the end of each month Ana adds up her fuel receipts and everyone pays an equal share. This month there are three receipts: 45.12, 38.90 and 27.41 EUR, a total of 111.43 EUR, for 412 km of commuting.
It is a small amount of money, which is exactly why it matters. Nobody wants to argue about cents with colleagues, so the split has to be correct without anyone checking it. And it has to add up: if the four shares come to less than the receipts, Ana pays the difference every single month without noticing.
We will keep amounts in cents, as whole numbers, because money must be exact and whole numbers are exact. The question of how to split 11143 cents four ways turns out to be the interesting part.
The Problem
Here is the first version a beginner might write. It adds up the receipts, divides by the number of people, and prints how much each person pays and how much that collects in total.
Create a folder for the program and the file inside it:
mkdir carpool
touch carpool/main.go
Put this in carpool/main.go:
package main
import "fmt"
func main() {
receipts := 4512 + 3890 + 2741 // fuel receipts this month, in cents
people := 4
share := receipts / people
fmt.Println("Fuel this month (cents):", receipts)
fmt.Println("Each person pays (cents):", share)
fmt.Println("Collected (cents):", share*people)
}
Go into the folder and run it:
cd carpool
go run .
Fuel this month (cents): 11143
Each person pays (cents): 2785
Collected (cents): 11140
The program ran, and the numbers do not add up. The fuel cost 11143 cents, four people pay 2785 cents each, and that collects 11140 cents. Three cents are missing, and since Ana paid at the pump, they come out of her pocket. Next month it happens again.
Let's read the program before we fix it. package main says this file belongs to the program package. import "fmt" brings in the formatting package. func main() is where execution starts. receipts := 4512 + 3890 + 2741 creates an int holding the total, 11143; the text after // is a comment. people := 4 creates another int.
The bug is in share := receipts / people. When both sides of / are integers, Go performs integer division: it divides and throws away the fractional part. 11143 divided by 4 is 2785.75, and throwing away the .75 leaves 2785. Nothing warns about it, because integer division is a perfectly normal thing to want. The three cents are the .75 multiplied back by four.
fmt.Println prints its arguments separated by spaces, followed by a newline, which is why "Collected (cents):" and 11140 appear with a space between them. share*people is calculated right there in the call.
Before we fix the arithmetic, let's understand what go run . actually did.
What go run and go build Do
go run . means "compile the package in the current folder and run it". The . is the current folder. Behind the scenes Go compiled main.go into an executable in a temporary folder, ran it, and deleted it. That is convenient while you are working, but every go run compiles again from scratch.
To get an executable you can keep, run go build, then list the folder and run the result:
go build && ls -1 && ./carpool
carpool
main.go
Fuel this month (cents): 11143
Each person pays (cents): 2785
Collected (cents): 11140
go build wrote a file named carpool, after the folder, next to main.go. && is a shell operator that runs the next command only if the previous one succeeded, so if compilation fails you see the errors instead of running an old file. ./carpool runs the new executable; the ./ means "the file in this folder".
The executable is a complete program. Check its size:
ls -l carpool | awk '{print $5}'
2254764
About 2.2 MB for a program of a dozen lines. That is because Go puts everything the program needs into this one file: our code, the parts of fmt it uses, and Go's runtime, the code that manages memory and starts the program. You could copy this single file to another Linux machine of the same kind and run it there without installing Go.
Now look at how the compiler finds the program. Every runnable Go program needs both a package called main and a function called main in it. Change the first line of main.go to package carpool and run it:
go run .
package learning/carpool is not a main package
learning/carpool is the full name of our package: the module name from go.mod, learning, plus the folder name, carpool. Because the package is no longer called main, Go treats it as a library, something other code would import, and refuses to run it. Change the first line back to package main.
Try it: Rename the function instead: change func main() { to func Main() { and run go run .. Predict the message before you look. You get function main is undeclared in the main package, because Go looks for a function named exactly main, lower case, and names in Go are case-sensitive. Change it back to main.
Go's Strict Compiler: Unused Variables and Imports
Go's compiler is stricter than most about code that does nothing. Let's see it. Add a line that records who the driver is, right after people := 4, so the top of main reads:
receipts := 4512 + 3890 + 2741 // fuel receipts this month, in cents
people := 4
driver := "Ana"
go run .
# learning/carpool
./main.go:8:2: declared and not used: driver
The program does not compile. Let's take the message apart, since every Go compiler error has this shape.
# learning/carpoolnames the package that failed to compile../main.go:8:2is the location: filemain.goin the current folder, line 8, column 2. Column 2 is wheredriverstarts, after the tab that indents it.declared and not used: driveris the complaint: we created a variable and never read it.
In many languages that is at most a warning. In Go it is an error, by design. A variable that is set and never read is almost always a mistake: a name typed wrong further down, a calculation someone forgot to finish, a value left over from code that was removed. Go's authors decided that such code should not compile, so the mistake is found immediately instead of months later.
Delete the driver line. The same rule applies to imports. Change the import to bring in a second package that the program does not use:
import (
"fmt"
"math"
)
go run .
# learning/carpool
./main.go:5:2: "math" imported and not used
The parenthesised form is how you import several packages; each goes on its own line. An unused import is an error for the same reason, and also because every import makes the program take longer to compile and larger to ship. Change the import back to import "fmt".
Sometimes you really do want to ignore a value, for example while a program is half-written. Go gives you the blank identifier _ for that: assigning to _ throws the value away and counts as using it. If you add driver := "Ana" and then _ = driver on the next line, the program compiles again. Use it deliberately and rarely; most of the time the error is telling you something.
Try it: Under share := receipts / people, add the line share := receipts % people, as if you wanted to reuse the name for something else. Predict whether it is the "not used" error or something different. It is different: ./main.go:10:8: no new variables on left side of :=. := declares new variables, and share already exists, so Go refuses to declare it twice. To change an existing variable you would write share = ... with plain =. Remove the line.
Where the Cents Went: Division and Remainder
Now the real bug. Integer division gives each person 2785 cents and drops the rest. The rest is not lost in the arithmetic, though: Go has an operator that gives it to you. % is the remainder operator. 11143 % 4 is what is left after taking out as many fours as possible, which is 3. Those are exactly the three missing cents.
The fair fix is to give each person the integer share, then add one extra cent to the first remainder people. With 3 left over, three people pay 2786 and one pays 2785, and the total is exactly 11143. To do that we need the people as a list. Replace the whole of main.go with:
package main
import "fmt"
func main() {
receipts := 4512 + 3890 + 2741 // fuel receipts this month, in cents
people := []string{"Ana", "Bogdan", "Carla", "Dan"}
share := receipts / len(people)
remainder := receipts % len(people)
collected := 0
for i, name := range people {
amount := share
if i < remainder {
amount++
}
fmt.Printf("%-7s pays %d.%02d EUR\n", name, amount/100, amount%100)
collected += amount
}
fmt.Printf("Fuel: %d.%02d EUR\n", receipts/100, receipts%100)
fmt.Printf("Collected: %d.%02d EUR\n", collected/100, collected%100)
}
go run .
Ana pays 27.86 EUR
Bogdan pays 27.86 EUR
Carla pays 27.86 EUR
Dan pays 27.85 EUR
Fuel: 111.43 EUR
Collected: 111.43 EUR
The shares now add up to exactly the fuel bill. Let's go through the new pieces.
people := []string{"Ana", "Bogdan", "Carla", "Dan"}creates a slice, Go's ordinary list type.[]stringmeans "a slice of strings", and the values in braces are its elements.len(people)is its length, 4, so the number of people now comes from the list itself and cannot disagree with it.share := receipts / len(people)is the same integer division as before, 2785.remainder := receipts % len(people)is the leftover, 3.collected := 0starts a running total, so the program can prove that the shares add up.for i, name := range peopleloops over the slice. On each pass,iis the position, starting at 0, andnameis the element at that position. So the passes see0 Ana,1 Bogdan,2 Carla,3 Dan.amount := sharestarts each person at the base share, andif i < remainder { amount++ }adds one cent for positions 0, 1 and 2, the first three people.amount++is short foramount = amount + 1.collected += amountadds this person's amount to the total.
The printing now uses fmt.Printf, which takes a format string with placeholders called verbs, each starting with %, followed by the values that fill them in order.
%-7sprints a string in a field 7 characters wide, and the-means left-aligned, padded with spaces on the right. That is why the wordpayslines up in every row.%d.%02dprints euros and cents.amount/100is integer division again, used on purpose this time: 2786 / 100 is 27, the euros.amount%100is the remainder, 86, the cents.%02dpads the cents with a leading zero to two digits, so 5 cents prints as05, not5.\nends the line. UnlikePrintln,Printfdoes not add a newline by itself.
Try it: Delete the three lines of the if i < remainder block and run go run .. Predict the output. You might expect everyone to pay 27.85 again, but the program does not compile: declared and not used: remainder and declared and not used: i. Without the if, nothing reads remainder or i any more, and Go's strict compiler points straight at the logic you just removed. Put the block back.
Mixing int and float64: Go Never Converts for You
The colleagues want one more number on the summary: the cost per kilometre, to compare with taking the train. That needs a fraction, and our values are all integers. Add these lines at the end of main, after the Collected line:
km := 412
perKm := receipts / km
fmt.Println("Cost per km (cents):", perKm)
go run .
Ana pays 27.86 EUR
Bogdan pays 27.86 EUR
Carla pays 27.86 EUR
Dan pays 27.85 EUR
Fuel: 111.43 EUR
Collected: 111.43 EUR
Cost per km (cents): 27
27 cents per km is close, but it is integer division again: 11143 / 412 is 27.046..., and the fraction is gone. For a comparison with train fares we want euros with decimals, so we need a float64. The obvious attempt is to convert the receipts and divide. Change the perKm line and the print line to:
perKm := float64(receipts) / 100 / km
fmt.Println("Cost per km (EUR):", perKm)
go run .
# learning/carpool
./main.go:26:11: invalid operation: float64(receipts) / 100 / km (mismatched types float64 and int)
float64(receipts) is a conversion: it takes the int 11143 and produces the float64 11143.0. Dividing that by 100 works. But then it is divided by km, which is an int, and Go refuses: "mismatched types float64 and int". Many languages would quietly convert the int to a float here. Go never converts between numeric types on its own, because each silent conversion is a place where precision can be lost or a value can change without anyone deciding it should.
You might be wondering why dividing by 100 was fine. A number written directly in the code, like 100, is an untyped constant: it has no fixed type until it is used, and Go gives it whatever type the expression needs, here float64. A variable like km already has a type, int, and keeps it.
The fix is to say what we mean and convert km as well:
perKm := float64(receipts) / 100 / float64(km)
go run .
Ana pays 27.86 EUR
Bogdan pays 27.86 EUR
Carla pays 27.86 EUR
Dan pays 27.85 EUR
Fuel: 111.43 EUR
Collected: 111.43 EUR
Cost per km (EUR): 0.27046116504854373
Now every operand is a float64, so the division keeps its fraction: 111.43 EUR over 412 km is 0.2704... EUR per km. Println prints a float64 with as many digits as needed to represent it exactly, which is why there are so many. We will format it properly in the next section.
Note: Untyped constants can surprise you the other way, too. receipts / 100.0 / km compiles, because 100.0 is a whole number in value, so Go happily treats it as the int 100. The whole expression is then integer arithmetic, and the result is 0. Writing a decimal point does not make an expression floating-point in Go; only a float64 operand does.
Try it: Change the line to perKm := float64(receipts / 100 / km), converting the whole expression instead of its parts. Predict the printed value. It is Cost per km (EUR): 0. The parentheses make the division happen first, entirely in integers (11143 / 100 is 111, and 111 / 412 is 0), and only the final 0 is converted. A conversion cannot bring back a fraction that integer division already threw away. Put the per-operand version back.
Printf Verbs and go vet
The last step is to print the cost per km as money, with two decimals. Change the print line to use Printf, but with the verb we have been using all along:
fmt.Printf("Cost per km: %d EUR\n", perKm)
go run .
Ana pays 27.86 EUR
Bogdan pays 27.86 EUR
Carla pays 27.86 EUR
Dan pays 27.85 EUR
Fuel: 111.43 EUR
Collected: 111.43 EUR
Cost per km: %!d(float64=0.27046116504854373) EUR
It compiled and ran, and the last line is garbled. %d is the verb for integers, and perKm is a float64. The compiler does not check format strings: to it, Printf is just a function taking a string and some values. So the mistake reaches the running program, and fmt reports it inside the output: %!d(...) means "the verb %d could not print this value", followed by the value's type and value. It is a helpful message, but it would appear on the screen for the carpool to read.
This is what go vet is for. It is part of the standard go tool, and it looks for code that compiles but is very likely wrong. Run it:
go vet .
# learning/carpool
# [learning/carpool]
./main.go:27:27: fmt.Printf format %d has arg perKm of wrong type float64
go vet understands fmt's verbs and checks each one against the type of its argument, which is exactly the check the compiler does not do. The location points at the format string on line 27. The message says what is wrong in plain terms: %d was given perKm, which is a float64.
The verb for a float64 is %f, and %.2f means "with exactly two digits after the decimal point". Change the line to:
fmt.Printf("Cost per km: %.2f EUR\n", perKm)
Now check with go vet and run, in one command:
go vet . && go run .
Ana pays 27.86 EUR
Bogdan pays 27.86 EUR
Carla pays 27.86 EUR
Dan pays 27.85 EUR
Fuel: 111.43 EUR
Collected: 111.43 EUR
Cost per km: 0.27 EUR
go vet printed nothing, which means it found nothing, so && went on to run the program. The cost per km is 0.27 EUR, rounded to two decimals by %.2f. That is a good habit to keep: run go vet . before you trust a program, especially one that uses Printf.
Try it: In the line that prints each person's share, delete the last argument, amount%100, so the call has two verbs for cents and euros but only one value to fill them. Run go run . and then go vet ., and predict both outputs. The program prints pays 27.%!d(MISSING) EUR for everyone, because the second verb has no value, and go vet reports fmt.Printf format %02d reads arg #3, but call has 2 args. Put the argument back.
Summary
We wrote a program that splits a carpool's fuel bill so the shares always add up to the receipts, and used it to learn how Go programs are run, built and checked. We kept the receipts in the code to focus on the language. Reading them from a file or from the command line, and splitting by distance instead of equally, are natural next steps.
- A Go program is a package named
mainwith a function namedmain.go run .compiles and runs the package in the current folder;go buildleaves a self-contained executable named after the folder. - An unused variable or an unused import is a compile error in Go. It almost always points at a real mistake; the blank identifier
_is there for the rare cases where ignoring a value is intended. :=declares a new variable and infers its type; it cannot be used again for a name that already exists in the same scope, where plain=assigns.- Dividing two
intvalues discards the fraction. Use%to get the remainder, and when splitting money, distribute the remainder explicitly so the parts add up to the whole. - Go never converts between
intandfloat64by itself. Convert each operand withfloat64(...)before dividing; converting after an integer division is too late. - Constants written in the code are untyped and take whatever type the expression needs, so a decimal point alone does not make an expression floating-point.
fmt.Printfverbs must match their values:%dfor integers,%sfor strings,%.2ffor afloat64with two decimals, and a width such as%-7sor%02dfor alignment and padding.- The compiler does not check format strings;
go vet .does, and it is worth running before trusting any program that prints withPrintf.