SyntaxPilot
Courses/Go Programming/Lesson 1

Go Programming · Lesson 1 of 89 · 17 min

Why Go, where it is used, and your first program

Go's history (Google, 2009, Griesemer, Pike, Thompson)design goals (simplicity, fast builds, concurrency)compiledstatically typedgarbage collectedwhere Go is used (Docker, Kubernetes, Terraform, cloud backends, CLIs)package mainfunc mainimportfmt.Printlncommentssemicolon insertiongofmt

These are the notes for Go episode 1. You will learn why Google created Go, what "compiled", "statically typed" and "garbage collected" mean, where Go is used in the real world, and how to write, run and fix your first Go program. Every example below runs as-is in the SyntaxPilot compiler (language: Go, which runs your code with go run main.go). The outputs and error messages are copied from real runs (Go 1.24).

First, two words

  • A program is a list of instructions the computer follows one by one, in order. Like a recipe: step 1, step 2, step 3.
  • A programming language is the set of words and grammar rules we use to write those instructions. Go is one of them.
  • Source code is the text of a program, written by a person (for example, the file main.go).

The problem: the giant kitchen

Picture a giant restaurant kitchen: thousands of cooks and one enormous recipe book. That was Google's software in 2007: huge programs worked on by thousands of engineers. Three things hurt:

In the kitchen In software
Change one line of a recipe, wait ages before cooking can start Large programs took a long time to build (prepare to run), and builds were complicated
Many stoves, but recipes written for one cook CPUs gained many cores (processors side by side), but most languages were designed for one task at a time
The recipe book is so complex that new cooks get lost Languages had grown complicated and code was hard to read

The Go FAQ says it directly: Go "was born out of frustration with existing languages and environments for the work we were doing at Google", including "the undue complexity required to build large software projects", and "the rise of multicore CPUs argued that a language should provide first-class support" for concurrency.

The fix: a new language

Date What happened
21 September 2007 Robert Griesemer, Rob Pike and Ken Thompson start sketching the goals for a new language on a whiteboard at Google
January 2008 Ken Thompson starts work on a compiler to explore the ideas
10 November 2009 Go becomes a public open source project
  • Open source means the language's own code is public: anyone can use it, read it and improve it, for free.
  • The mascot, the gopher, was designed by the artist Renée French. Go programmers are often called gophers.
  • Go or Golang? The language is called Go. "Golang" comes from its original website, golang.org. Both names mean the same language.

Go's three design goals

Goal What it means Kitchen fix
Simple a small language with few keywords; easy to read anyone's code a short, clear recipe book
Fast builds the Go team's aim: "it should take at most a few seconds to build a large executable on a single computer" no long wait after every change
Concurrency handling many tasks at overlapping times, built into the language one chef keeping rice, dal and rotis going together

Three big words

Compiled: translate the whole book once

A recipe book in English is useless to a cook who reads only Tamil. Your computer's processor (the CPU) only understands machine code, raw numbers. It cannot read source code.

Recipe book Go
Book in English, cook reads Tamil Source code; the CPU reads only machine code
Translate the whole book once, before cooking The compiler translates all your code ahead of time
The cook uses the Tamil copy, no translator needed The executable: a file that runs on its own, fast
  • A compiler is a program that checks your source code and translates it into machine code.
  • An executable is the resulting file the computer can run directly.
  • Go is a compiled language. When you press Run in the SyntaxPilot compiler, it runs go run main.go, which compiles your code and then runs it.

Statically typed: labelled jars, checked before cooking

Every jar in a good kitchen has a label: sugar, salt, rice. In Go, every value has a type: the kind of thing it is. Text is the type string; a whole number is the type int. Static typing means types are checked before the program runs, by the compiler.

package main

import "fmt"

func main() {
    fmt.Println("Start")
    fmt.Println("Age: " + 21)
}

Output:

# command-line-arguments
./main.go:7:17: invalid operation: "Age: " + 21 (mismatched types untyped string and untyped int)

Notice that Start was never printed: the compiler refused the whole program before anything ran. Go never mixes text and numbers by itself. Give Println the two values separately, with a comma:

fmt.Println("Start")
fmt.Println("Age:", 21)
Start
Age: 21

Garbage collected: a helper clears the plates

While a program runs, it keeps its data in memory, like table space in a restaurant. If nobody cleared empty plates, the restaurant would fill up and stop. In some languages you clear every plate yourself. Go has a garbage collector: a part of the Go runtime that finds memory nobody uses any more and frees it automatically.

Go in one breath

  1. Compiled: translated to machine code before running.
  2. Statically typed: type mistakes caught before running.
  3. Garbage collected: unused memory freed for you.

All in a simple language with fast builds and concurrency built in.

Where Go is used

Software What it does Written in Go?
Docker packs an app and everything it needs into a box called a container yes (go.dev)
Kubernetes runs and manages thousands of containers across many machines predominantly Go
Terraform creates cloud servers and services from text files yes (go.dev)
Prometheus monitors servers and apps and raises alerts most components (go.dev)
etcd a distributed key-value store yes (go.dev)

Go is also widely used for:

  • Backends: the server side of apps, the part that answers requests from your phone or browser (often called APIs and web services).
  • Command-line tools (CLIs): programs you run by typing commands in a terminal.

Your first program, one error at a time

The goal: print Hello, World!.

Attempt 1: just the print line

fmt.Println("Hello, World!")
main.go:1:1: expected 'package', found fmt

Why: every Go file must start by naming its package. A package is a group of related Go code with a name, like a labelled box when you move house. The special package main is the one that becomes a runnable program.

Attempt 2: add the package clause

package main

fmt.Println("Hello, World!")
# command-line-arguments
./main.go:3:1: syntax error: non-declaration statement outside function body

Why: syntax means the grammar of the language. An instruction like fmt.Println(...) cannot float around in the file; it must live inside a function: a named block of instructions, like a recipe card called "Make chai" with its steps underneath. A program needs one starting point: the function main.

Attempt 3: add func main

package main

func main() {
    fmt.Println("Hello, World!")
}
# command-line-arguments
./main.go:4:5: undefined: fmt

Why: fmt is a toolbox (a package) from Go's standard library, the ready-made packages that come with Go. You must bring it in with import, like a carpenter fetching a toolbox from the store room.

Attempt 4: import "fmt" — it works

package main

import "fmt"

func main() {
    fmt.Println("Hello, World!")
}
Hello, World!

Every runnable Go program has this shape

Line Meaning
package main this file belongs to the main package, the runnable one
import "fmt" bring in the fmt (format) package
func main() { ... } the starting point; the instructions inside { } run top to bottom

Anatomy of fmt.Println("Hi")

Piece Meaning
fmt the package we imported (say it "fumpt", "format" or "F M T")
. "from inside": the Println that lives in fmt
Println a function: print the values, then move to a new line ("print line")
( ) calling the function: running it
"Hi" a string: text in double quotes, printed without the quotes

Names matter

Go is case sensitive: main and Main are different names, just as the password chai123 is not Chai123.

Code Real error Why
package hello (with func main) package command-line-arguments is not a main package only package main can run; command-line-arguments is the name go run gives the file
func Main() runtime.main_main·f: function main is undeclared in the main package the start function must be main, small m; undeclared = never created
fmt.println("Hi") ./main.go:6:9: undefined: fmt.println the function is Println

A name starting with a capital letter is exported: visible outside its package. That is why Println is capitalised: so your code can use it from the fmt package.

Text vs numbers: whiteboard vs calculator

package main

import "fmt"

func main() {
    fmt.Println("5 + 3")
    fmt.Println(5 + 3)
    fmt.Println("Age:", 21)
}
5 + 3
8
Age: 21
  • In quotes = text, printed as written (a whiteboard).
  • No quotes = calculated (a calculator).
  • Several values separated by commas are printed with a space between them.

Semicolons and the brace rule

Java and C end every statement (one complete instruction) with ;. Go's grammar uses semicolons too, but the compiler inserts them automatically at the end of a line that looks complete. The Go FAQ: "Semicolons, however, are for parsers, not for people." (A parser is the part of the compiler that reads the grammar.)

The famous trap: putting { on the next line.

func main()
{
    fmt.Println("Hello, World!")
}
# command-line-arguments
./main.go:6:1: syntax error: unexpected semicolon or newline before {

func main() looked complete, so a semicolon was inserted after it. In Go, the opening brace always stays on the same line.

gofmt: one style for everyone

gofmt (and go fmt, which runs it on a package) rewrites a file in Go's single official style: tabs for indentation, standard spacing. Before:

package main
import "fmt"
func main(){
fmt.Println("Hi")   // greet
  fmt.Println( "Bye" ) }

After gofmt:

package main

import "fmt"

func main() {
    fmt.Println("Hi") // greet
    fmt.Println("Bye")
}

Most Go editors run it every time you save, so Go code everywhere looks the same.

Unused imports are errors

package main

import (
    "fmt"
    "os"
)

func main() {
    fmt.Println("Hi")
}
# command-line-arguments
./main.go:5:5: "os" imported and not used

In many languages this is a warning; in Go it is an error. Several imports are grouped inside import ( ... ), one per line.

Comments

package main

import "fmt"

// main is where the program starts.
func main() {
    fmt.Println("Hello") // greet
    /* switched off:
    fmt.Println("Not printed") */
    fmt.Println("Bye")
}
Hello
Bye
  • // starts a comment to the end of the line.
  • /* ... */ can span many lines.
  • A comment right above a declaration, starting with its name, is a doc comment; Go's tools turn it into documentation (episode 2).

Common mistakes (and the real error messages)

You wrote Real error Fix
fmt.Println("Hi") alone expected 'package', found fmt start with package main
a statement outside a function syntax error: non-declaration statement outside function body put it inside func main() { }
no import undefined: fmt import "fmt"
func main() then { on the next line syntax error: unexpected semicolon or newline before { func main() {
func Main() function main is undeclared in the main package func main()
fmt.println undefined: fmt.println fmt.Println
"Age: " + 21 invalid operation: "Age: " + 21 (mismatched types untyped string and untyped int) fmt.Println("Age:", 21)
an unused import "os" imported and not used delete the import

Mini project: a profile card

strings.Repeat("=", 30) from the strings package returns = repeated 30 times, like a photocopier.

package main

import (
    "fmt"
    "strings"
)

func main() {
    // Mini project: my profile card
    fmt.Println(strings.Repeat("=", 30))
    fmt.Println("  Name : Aarav")
    fmt.Println("  City : Pune")
    fmt.Println("  Goal : Go developer")
    fmt.Println(strings.Repeat("=", 30))
}
==============================
  Name : Aarav
  City : Pune
  Goal : Go developer
==============================

Practice

  1. Print your name, age and city on one line using commas.
  2. Make a border of 20 * characters with strings.Repeat.
  3. Predict, then run: fmt.Println("10", 10+5).
  4. Break the Hello World program three ways on purpose (remove package main, remove the import, move { to the next line) and write down each error.
Solutions and hints
  1. fmt.Println("Aarav", 21, "Pune") prints Aarav 21 Pune.
  2. Import both fmt and strings, then fmt.Println(strings.Repeat("*", 20)).
  3. 10 15: the first value is text, the second is calculated, and the comma adds a space.
  4. expected 'package', found fmt; undefined: fmt; syntax error: unexpected semicolon or newline before {.

Quick quiz

What does this print?

package main

import "fmt"

func main() {
    fmt.Println("2 + 3", 2+3)
}
  • A. 2 + 3 2 + 3
  • B. 5 5
  • C. 2 + 3 5
  • D. Compile error
Answer

C. The first value is in quotes, so it prints as written. The second is calculated: 5. Println puts a space between values.

Interview questions

  • Who created Go, when, and why? (Griesemer, Pike and Thompson at Google, from 2007; open source in 2009; slow complex builds, multicore CPUs, complexity.)
  • Is Go compiled or interpreted? What does "statically typed" mean?
  • What is garbage collection, and what problem does it solve?
  • Why must a runnable Go program use package main and func main?
  • Why does Go reject unused imports? Why must { be on the same line as func main()?
  • What does a capital first letter mean for a Go identifier? (It is exported.)

Glossary

Term Meaning Example
Program a list of instructions the computer runs in order a recipe for the computer
Programming language the words and grammar used to write programs Go, Java, Python
Source code the text of a program, written by a person main.go
Go / Golang a compiled, statically typed, garbage-collected language from Google; "Golang" is a nickname go run main.go
Open source the code is public; anyone can use, read and improve it Go since 10 Nov 2009
Build preparing a program to run (checking and compiling it) go build
CPU / core the processor / one of several processors on a chip a 4-core laptop
Concurrency handling many tasks at overlapping times one chef, three dishes
Machine code the raw numeric instructions a CPU understands what the compiler produces
Compiler translates source code into machine code ahead of time the Go compiler
Compiled language a language translated fully before running Go, C
Executable a file the computer can run directly the file go build makes
Type the kind of a value string, int
Statically typed types are checked by the compiler before running "Age: " + 21 is rejected
string text in double quotes "Hello"
int a whole number 21
Memory where a running program keeps its data table space
Garbage collector frees memory that nothing uses any more, automatically Go's runtime
Container an app packed with everything it needs a Docker container
Backend the server side of an app an API answering your phone
CLI a command-line tool, used by typing commands go, docker
Package a named group of related Go code; every file starts with package package main
package main the package that becomes a runnable program package main
Function a named block of instructions func main() { }
func main the function where a program starts func main() { ... }
Standard library ready-made packages that come with Go fmt, strings, os
import brings a package into your file import "fmt"
fmt Go's formatting/printing package fmt.Println
fmt.Println prints values separated by spaces, then a newline fmt.Println("Hi", 5)
Call running a function by writing () after its name fmt.Println()
Syntax the grammar rules of a language { must be on the same line
Statement one complete instruction fmt.Println("Hi")
Case sensitive capital and small letters are different main ≠ Main
Exported a name starting with a capital letter, visible outside its package Println, Repeat
Undeclared / undefined a name that was never created / that Go can't find undefined: fmt
Semicolon insertion the compiler adds ; at the end of lines that look complete why { stays on the same line
Parser the part of the compiler that reads the grammar
gofmt / go fmt the official formatter / the command that runs it on a package go fmt
Comment a note for humans the compiler ignores // note, /* note */
Doc comment a comment above a declaration that becomes documentation // main is where...
strings.Repeat returns a string repeated n times strings.Repeat("=", 30)

Summary

  • Go was sketched at Google in 2007 by Griesemer, Pike and Thompson and released as open source on 10 November 2009, to fix slow, complex builds and to embrace multicore CPUs.
  • Goals: simple, fast builds, concurrency built in. Go is compiled, statically typed and garbage collected.
  • Used in Docker, Kubernetes, Terraform, Prometheus, cloud backends and CLIs.
  • Every runnable program: package main, import "fmt", func main() { ... }.
  • Quotes = text, no quotes = calculated; commas print values with spaces.
  • { stays on the same line (semicolon insertion); gofmt formats code; unused imports are errors.

Next episode: the Go toolchain. Your friend wants your program, but sending main.go doesn't work, so you meet go run, go build, modules, go vet, and building a Windows .exe from Linux.

Sources: the Go FAQ (go.dev/doc/faq) for the history, goals, garbage collection, semicolons and mascot; go.dev/solutions/devops for Docker, Terraform, Prometheus and etcd; collabnix.com for Kubernetes being predominantly Go.