Go · Chapter 1 of 26

Go, and your first program

By the end of this chapter you can say why BijliGo writes its backend in Go, write a Go program with package main and func main, run it with go run and build it with go build, print with fmt, keep values in variables made with := and var, use Go's basic types (int, float64, string and bool), and read the compiler's errors as help, not as a wall. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: The language
  • 4 tasks
  • Go
  • Free chapter

Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.

Why you need this

BijliGo runs 1,180 electric vehicle chargers at 240 stations: 228 in Bengaluru (in mall car parks, metro stations, tech parks and apartment blocks), six in Mysuru and six on the expressway between the two cities. Cars, autos and scooters plug in all day, and most of all from 6 pm to 10 pm, when 2,128 of Wednesday's 3,600 sessions started.

Every charger talks to BijliGo's ingest service all the time: a heartbeat every 30 seconds ("I am alive"), and a meter reading every 10 seconds while a vehicle charges. The service BijliGo has today handles those messages one at a time. On Wednesday evening the line of waiting messages grew longer than 30 seconds, chargers that heard nothing back marked themselves offline, and drivers stood next to chargers that would not start. Tenzin, who was on call, was paged at 7:12 pm. Pooja, who runs finance and operations, spent Thursday crediting the wallets of drivers whose sessions had failed: 109 of them that day. Nandini, the founder, wants the next evening peak to be a quiet one.

A faster server would only make the line move a little quicker. What the ingest service needs is to handle every charger at once, cheaply, and to be a small program that starts in a moment and is easy to run on many machines. Joseph, BijliGo's staff engineer, is rewriting it in Go, and you write it with him. You do not need to have used Go before: if you have written a little Python or JavaScript, this lab starts from there.

The lesson

One service, many chargers

Your lab can show you the difference. lab heartbeats makes 1,180 heartbeats, one for each charger, where recording one takes the server 5 ms (a write to the database). It records them one at a time, like today's service, and then all at once:

$ lab heartbeats
1180 chargers each sent a heartbeat. Recording one takes the server 5 ms.
One at a time: 6.77 s
All at once:   8.4 ms, with 1180 goroutines (2.4 MB of memory for their stacks)

One at a time, the last charger waited almost 7 seconds, while every charging vehicle sends a new meter reading every 10 seconds: the line never empties. All at once, every heartbeat was recorded in about the time one takes. Each "at once" was a goroutine, Go's way of running a function alongside the others, and 1,180 of them cost 2.4 MB of memory. You write goroutines yourself in chapter 15; first, the language.

What Go is

Go is a programming language made at Google and released in 2009 for exactly this kind of work: network services that many machines run.

  • Compiled: the go tool turns your source code into a program file that the computer runs directly. Mistakes in types and names are found before the program ever runs.
  • Statically typed: every variable has one type, fixed when the program is compiled.
  • Small: the whole language has 25 keywords, and there is usually one plain way to write a thing.
  • Batteries included: an HTTP server, JSON, testing and the race detector are in the standard library and the go tool, all used later in this lab.

Your first program

Every Go program you run starts like this one, hello.go:

package main

import "fmt"

func main() {
	fmt.Println("Namaste from BijliGo")
}
$ go run hello.go
Namaste from BijliGo
  • package main says this file is a program, not a library. Every Go file starts with the package it belongs to.
  • import "fmt" brings in the standard library's fmt package (format), which prints.
  • func main() is where the program starts, and when main returns, the program ends. The code inside sits between braces.
  • fmt.Println is the function Println from the package fmt. It prints its values and then a line break.

The opening brace must sit on the same line as func main(). Go adds the semicolons that end statements for you, at the end of lines, so a brace on the next line breaks the program:

$ go run brace.go
# command-line-arguments
./brace.go:6:1: syntax error: unexpected semicolon or newline before {

Forget the import and Go does not know the name:

$ go run noimport.go
# command-line-arguments
./noimport.go:4:2: undefined: fmt

Every error starts with the file, the line and the column (noimport.go:4:2 is line 4, column 2). Go code is indented with tabs; gofmt -w hello.go lays any file out the one standard Go way.

go run and go build

go run hello.go does two things: it compiles the file into a program, then runs it. go build does only the first part and keeps the program as a file you can run again and again:

$ time go build hello.go

real	0m0.092s
$ ls -l hello
-rwxr-xr-x 1 student student 2342053 Oct 23 06:25 hello
$ time ./hello
Namaste from BijliGo

real	0m0.001s

The build took 0.092 s here. The program is one file of 2.3 MB that holds everything it needs, so you can copy it to another Linux machine and run it there: no Go installed, nothing else to install. It started and finished in a millisecond. That is why Go services are easy to ship and quick to start when the evening peak needs more of them.

In this chapter every file is a whole program with its own func main, so you run each one by name: go run welcome.go.

Printing with fmt

fmt.Println("Stations:", 240, "Chargers:", 1180)
fmt.Print("Koramangala Mall")
fmt.Print(" is open\n")
fmt.Printf("%s has %d chargers\n", "Koramangala Mall", 8)
fmt.Printf("%.1f kWh, fast: %t\n", 11.7, true)
fmt.Printf("%v | %v | %v\n", "C1002", 60.0, false)
Stations: 240 Chargers: 1180
Koramangala Mall is open
Koramangala Mall has 8 chargers
11.7 kWh, fast: true
C1002 | 60 | false
  • Println prints any number of values, of any type, with a space between them and a line break at the end.
  • Print adds no line break; \n inside the quotes is one.
  • Printf fills a pattern: each % verb takes the next value. %s is a string, %d a whole number, %t true or false, %v any value in its plain form, and %.1f a decimal number with one digit after the point (%.2f gives two). Printf adds no line break of its own.

Notice the last line: Println and %v print the decimal number 60.0 as 60. Chapter 2 meets all of fmt's verbs.

Variables

A variable is a name for a value. Go has two ways to make one:

station := "Koramangala Mall"
chargers := 8
var powerKW float64 = 60
var open bool
var sessions int
var note string

fmt.Println(station, chargers, powerKW)
fmt.Println(open, sessions, "["+note+"]")

chargers = 9
sessions = sessions + 1
fmt.Println(chargers, sessions)
Koramangala Mall 8 60
false 0 []
9 1
  • name := value makes a new variable inside a function, and Go works out its type from the value: 8 makes an int, "Koramangala Mall" a string.
  • var name type = value says the type yourself. Leave out the value and the variable starts at its type's zero value: 0 for numbers, false for a bool, the empty string "" for a string. A Go variable is never undefined.
  • = changes a variable that already exists; := makes a new one. + joins two strings.

The basic types

Four types carry this chapter:

typeholdsexamples
intwhole numbers1180, -3, 2400
float64decimal numbers7.4, 11.7
stringtext, in double quotes"C1002"
booltrue or falsefalse

Arithmetic on ints stays whole: / drops the remainder, and % gives the remainder. A decimal on either side makes a float64:

minutes := 157
fmt.Println(minutes/60, "h", minutes%60, "min")
fmt.Println(7/2, 7.0/2)
2 h 37 min
3 3.5

Decimal numbers are close, not exact:

a := 0.1
b := 0.2
fmt.Println(a + b)
0.30000000000000004

That is fine for kilowatts and wrong for money. So BijliGo keeps every amount as whole paise in an int: ₹24 a kWh is 2400, and a bill is never a fraction of a paisa off.

Go never mixes types on its own. An int and a float64 cannot be multiplied, and a variable keeps the type it was made with:

$ go run mismatch.go
# command-line-arguments
./mismatch.go:8:14: invalid operation: kwh * tariff (mismatched types float64 and int)
$ go run assign.go
# command-line-arguments
./assign.go:7:13: cannot use "eight" (untyped string constant) as int value in assignment
./assign.go:8:11: no new variables on left side of :=

To mix them, convert one yourself: float64(tariff) is the int tariff as a float64, and int(x) turns a float64 into an int by dropping its decimals. With kwh := 11.7 and tariff := 2400:

fmt.Println(kwh * float64(tariff))
28080

The compiler is on your side

Go refuses to build a program with an import it does not use or a variable it never reads:

package main

import (
	"fmt"
	"os"
)

func main() {
	station := "Koramangala Mall"
	faults := 0
	fmt.Println(station)
}
$ go run unused.go
# command-line-arguments
./unused.go:5:2: "os" imported and not used
./unused.go:10:2: declared and not used: faults

Other languages run that program and leave you to find the forgotten variable later, at 2 am. Go stops before the program exists. Every error you meet in this chapter is the compiler catching a mistake while it is still cheap: read the first one, go to its line and column, fix it, and run again. The rest often disappear with it.

Your turn

Four tasks, one file each, at the top. Task 1 prints the ingest service's two welcome lines (do not forget the import). Task 2 prints charger C1051's card from variables, with the faults count at its zero value. Task 3 works out a session's energy and bill from two variables: as given, the file does not compile, and the Check also runs it with other numbers, so compute everything from the variables. Task 4 is an interview question: Tenzin's night report will not compile, and once it does, it prints the wrong uptime. Joseph will ask why Go is so strict. Run each file with go run file.go and compare what it prints with the task.

What you build: 4 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    welcome.go: the ingest service says hello

    When BijliGo's ingest service starts, it prints two lines. Make welcome.go print exactly these two lines, in this order:

    BijliGo ingest is starting

    Watching 1180 chargers at 240 stations

    Printing needs the fmt package, so the file must import it under package main. Letters, spaces and numbers must match exactly, with nothing else printed. The Check builds and runs welcome.go on its own, as go run welcome.go does.

  2. Task 2

    charger.go: one charger's card

    Tenzin wants a card for charger C1051. Keep each fact in a variable and print the card from the variables: the id C1051, the station Sarjapur Road Metro, the power 7.4 kW (a float64), the tariff 1400 paise a kWh (an int), fast charger false (a bool), and the faults today. Declare at least one variable with :=, and declare the faults count with var, the type int and no value, so that it starts at Go's zero value.

    Print exactly these five lines:

    Charger C1051 at Sarjapur Road Metro

    Power: 7.4 kW

    Tariff: 1400 paise a kWh

    Fast charger: false

    Faults today: 0

    Go refuses to compile a variable that is never used, so every variable must appear in the card.

  3. Task 3

    bill.go: what a session costs

    A session on charger C1042 used 17385 watt-hours, in the variable wh, at 2000 paise a kWh, in the variable tariff. Keep the two lines wh := 17385 and tariff := 2000 exactly as they are, and work out from them, then print exactly:

    Energy: 17.385 kWh

    Cost: 34770 paise

    Cost: 347 rupees 70 paise

    The energy in kWh is wh divided by 1000, with its decimals. The cost in paise is wh times tariff divided by 1000, a whole number. The rupees are the whole hundreds of that cost and the paise what is left over.

    The Check also runs bill.go with wh := 5333 and tariff := 1400 in those two lines, and then it must print Energy: 5.333 kWh, Cost: 7466 paise and Cost: 74 rupees 66 paise. As given, the file does not compile, because Go refuses variables that are never used.

  4. Task 4 · interview question

    Interview: report.go, the report that will not build

    At 2 am Tenzin wrote report.go for the night's report, and it does not compile. Fix it so that it prints exactly:

    Chargers: 1180

    Offline: 37

    Faulted: 6

    Online: 1137

    Uptime: 96.36 percent

    Online means neither offline nor faulted. Uptime is online divided by chargers, times 100, with its decimals, printed with two digits after the point (the starter's Printf line does that). Keep the lines chargers := 1180, offline := 37 and faulted := 6 exactly as they are: the Check also runs report.go with offline := 59 and faulted := 11, and then the last two lines must be Online: 1110 and Uptime: 94.07 percent.

    Joseph will ask: why does Go refuse to compile a program with an unused import or variable, and why will it not put an int into a float64 until you say so?

What you will learn

  • Why Go: one small service that handles many requests at once.
  • package main and func main: the shape of every Go program.
  • go run and go build: compiling a program and running it.
  • fmt: printing with Println, Print and Printf.
  • Variables: := and var, and the zero value a var starts with.
  • The basic types: int, float64, string and bool, and why Go never mixes them on its own.
  • The compiler's errors: what they say and how to fix them.

More in The language

Build "Go, and your first program" yourself

BijliGo, a Bengaluru EV charging network, drops chargers at the evening peak. You rewrite its backend in Go. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.