L5 · LanguagesProgramming Languages 101 · part 2 of 6

Go 101: A Small Language for Big Systems

Go has very few features, and that's on purpose. Types, slices, interfaces, errors and goroutines: the core of the language in one post, with the reason behind each design choice.

Takumi Yamada
· 10 min read · 3 references
gogolangprogramming-languagesconcurrencybackend
Left: the word GO in light blue, leaning forward, with speed lines. Right: a painting of three cartoon gophers working around an old machine with a brain on top.
Left: the Go logo. Right: the Go gopher, the language's mascot, drawn by Renée French, who designed it, for Go's fifth birthday. Go programmers often call themselves gophers.Left, logo: The Go Authors, public domain (trademark), via Wikimedia Commons (original). Changes: placed on a background.Right, drawing: Renée French, CC BY 3.0, via Wikimedia Commons (original). Changes: cropped and resized.

Go was designed at Google in 2007 by Robert Griesemer, Rob Pike and Ken Thompson. The story goes that they started sketching it while they waited for a large C++ program to compile.

Round portraits of three men, with their names below: Robert Griesemer, Rob Pike and Ken Thompson.
Robert Griesemer, Rob Pike and Ken Thompson, who designed Go. Griesemer had worked on Google's V8 JavaScript engine and Java's HotSpot virtual machine. Pike and Thompson had worked together at Bell Labs, where Thompson created Unix with Dennis Ritchie, and in 1992 the two of them designed UTF-8, the text encoding most of the web uses today. The photos are from 2012, 2010 and the 1970s.Left photo: Eugene Zelenko, CC BY-SA 4.0, via Wikimedia Commons (original). Changes: cropped to a circle and placed on a card with the name; this crop is shared under CC BY-SA 4.0.Middle photo: Kevin Shockey, CC BY 2.0, via Wikimedia Commons (original). Changes: cropped to a circle and placed on a card with the name.Right photo: unknown photographer, from the Jargon File, public domain, via Wikimedia Commons (original). Changes: cropped to a circle and placed on a card with the name.

That story explains most of the language. Go is small on purpose. It has no inheritance, no , no operator overloading, no ? : operator, and only one kind of loop.

That list can make Go sound weak. The idea behind it is the opposite. If a language is small enough to keep entirely in your head, a team can read and change each other's code quickly. A lot of cloud software is written in Go, including , , Terraform and Prometheus, so the idea seems to have worked.

This post goes through the core of the language in order, with the reason behind each piece.

Hello, structure

Every Go file starts by naming its package, which is a group of files that belong together. Every program starts at the function main in the package main.

package main

import "fmt"

func main() {
    fmt.Println("hello, world")
}

Three things are worth noticing before we move on.

There are no semicolons. The adds them for you. That's also why the opening brace { has to be on the same line as func main().

A capital letter means public. fmt.Println starts with a capital letter, so other packages can use it. We say it's exported. A name that starts with a lowercase letter can only be used inside its own package. Go has no public or private keyword, because the first letter of the name does that job.

YOUR CODEpackage mainPACKAGE FMTPrintlnnewPrintercapital letter: exported, you can call itlowercase: private to its package
The first letter of a name decides who can use it.

Unused imports and variables are errors, not warnings. Go refuses to build code that contains things it doesn't use.

Run the program with go run main.go. Build it with go build and you get one executable file that runs on its own, with nothing else to install. That's a large part of why Go is so common for and command-line tools.

Variables and the zero value

var count int        // declared, equals 0
name := "gopher"     // declare and infer, inside functions only
const limit = 100    // constants are untyped until used

You will write the := form most of the time. It creates a variable and works out its type from the value.

The important idea here is the zero value. Every type in Go has a fixed default. Numbers start at 0, strings start empty, booleans start as false, and , and maps start as nil, which means "nothing". A Go variable always holds a known value, even if you never set one.

DECLARED WITH VAR, NEVER ASSIGNED0int""stringfalseboolnilpointernilslicenilmap
The zero value of six common types.

This prevents two common kinds of bugs. In C, a variable you forgot to set holds whatever were in that memory before. In Java, a field nobody set is , and using it crashes the program with a null pointer exception. Neither can happen in Go.

Good Go libraries are designed around this. A var buf bytes.Buffer can be used right away, with no setup call. The Go saying is "make the zero value useful".

Slices: the workhorse collection

Go has , but you will rarely write one. You will use slices, and one idea prevents most slice bugs.

A slice is not the data. A slice is a small window onto an array.

s := []int{10, 20, 30, 40, 50}
t := s[1:4]
Tptrlen 3cap 4Sptrlen 5cap 5UNDERLYING ARRAY1020304050t: len 3t: cap 4
s and t are two small headers over the same five numbers.

t didn't copy anything. It points into the same array as s. If you write t[0] = 99, then s[1] is 99 as well.

This is on purpose, and it's the reason slices exist. A slice is only three numbers: a pointer to the first element, a length, which is how many elements it shows, and a capacity, which is how much room the array has after that pointer. Passing a slice to a function copies those three numbers, not the data.

You add elements to a slice with append.

s := []int{}
for i := 0; i < 5; i++ {
    s = append(s, i*i)   // reassign, because append may move the data
}

When the array behind the slice is full, append creates a bigger array and copies the elements into it. The returned slice points at the new array, which is why you always assign the result back.

FULLlen 4, cap 40149no room for a fifthcopied into a bigger arrayappend(s, 16)len 5, cap 8014916room for three more
The fifth append in that loop. The returned slice points at the new array, which is why the result has to be kept.

You loop over a slice, or almost anything else, with range.

for i, v := range s {
    fmt.Println(i, v)
}

for is the only loop in Go. A while loop is written for cond {}.

Maps

A map stores values under keys, like a dictionary stores definitions under words.

ages := map[string]int{"ada": 36, "linus": 55}
ages["grace"] = 85

age, ok := ages["ada"]   // the comma ok idiom
if !ok {
    fmt.Println("not found")
}

Look at the line with age, ok. A map lookup can give you two values: the value, and a boolean that says whether the key was there. This is called the comma ok pattern, and Go uses it in several places. The lookup doesn't throw an error and doesn't return a special "not found" value. It hands you ok, and you decide what to do. If you ignore ok and the key is missing, you get the zero value.

THE MAP AGES"ada"36"linus"55"grace"85VALUEOKages["ada"]36truethe key is thereages["bob"]0falseno such key: thezero value, and false
Two lookups in the same map. The second value says whether the key was there.

Structs and methods: data first, behaviour attached

Go doesn't have classes. You define plain data with a struct, and then attach functions to it.

type Circle struct {
    Radius float64
}

func (c Circle) Area() float64 {
    return math.Pi * c.Radius * c.Radius
}

func (c *Circle) Scale(f float64) {
    c.Radius *= f
}

The (c Circle) before the function name is the receiver. It makes Area a method, so you can call it as circle.Area(). There is one decision to make for each method.

func (c Circle)  ...   value receiver:   method gets a COPY
func (c *Circle) ...   pointer receiver: method can MODIFY the original

Scale needs a pointer receiver. With a value receiver it would scale a copy of the circle and then throw the copy away. The usual rule is that if any method of a type needs a pointer receiver, all of its methods use one.

THE CALLER'S CIRCLEC, INSIDE SCALE(2)AFTERWARDSValue receiver(c Circle)Radius 2copiedRadius 4a copy, scaledRadius 2unchangedPointer receiver(c *Circle)Radius 2points at itits addressno copy is madeRadius 4scaled
The same call with each kind of receiver.

There is no inheritance. When you want to reuse a struct inside another one, you embed it.

type LoggedCircle struct {
    Circle          // embedded, so LoggedCircle now has Area() and Scale()
    Label  string
}

LoggedCircle now contains a whole Circle, and the methods of Circle can be called on a LoggedCircle directly. There are no class hierarchies and no overriding rules to learn. There are only fields, and methods that come along with them.

LOGGEDCIRCLECIRCLERadius float64Area() Scale(f)Label stringArea() and Scale()can be called on aLoggedCircle tooa field inside,not a parent class
Embedding puts one struct inside another. The inner struct's methods can be called on the outer one.

Interfaces: the best idea in the language

This is Go's most unusual design choice. An interface is a list of methods.

type Shape interface {
    Area() float64
}

Any type that has those methods fits the interface automatically. You don't write implements Shape anywhere. Circle has an Area() float64 method, so Circle is a Shape, and the compiler checks this where you use it.

This has three useful results.

You can write an interface for types you don't own. The 's io.Reader fits files, network connections, buffers, compressed streams and your own types. None of them had to know about each other.

The code that uses a type decides the interface. In Java you design interfaces first and make classes implement them. In Go you write concrete types first. Later, the code that needs to accept several types declares a small interface with only the methods it uses.

Small interfaces are normal. The most important interfaces in Go have exactly one method.

type Reader interface { Read(p []byte) (n int, err error) }
type Writer interface { Write(p []byte) (n int, err error) }

A large part of the standard library is built on those two. io.Copy(dst, src) can copy a file to a network connection, or a network connection into a hash, or a hash into a compressor. It doesn't need to know what is on either end.

a filea network connectiona buffera gzip streamyour own typeio.ReaderRead(p []byte)io.Copy(dst, src)only asks for Readeach of them has a Read method,and none of them names the interface
Nothing on the left declares that it implements io.Reader. Having the method is enough.

Errors are values, not events

Go has no exceptions. A function that can fail returns an error as one of its results, and you check it.

f, err := os.Open("config.json")
if err != nil {
    return fmt.Errorf("loading config: %w", err)
}
defer f.Close()

You will write if err != nil a lot. It's the most complained about part of Go, and it's a deliberate trade. What happens on failure is written in the code, right where the call is, every time. Nothing jumps out of the function without you seeing it.

Two parts of that code need a note.

fmt.Errorf with %w wraps the error. It adds a line of context in front of the original error, so the final message reads "loading config: open config.json: no such file". The functions errors.Is and errors.As can look inside that chain later.

loading config:added with %wopen config.json:from os.Openno such fileprinted as: loading config: open config.json: no such file
Each layer wraps the error underneath it and adds its own context in front.

defer f.Close() makes f.Close() run when the function returns, however it returns. So the cleanup is written right next to the line that opened the file.

Goroutines and channels: concurrency as a language feature

This is the reason many people choose Go. Starting a task that runs at the same time as the rest of the program takes one keyword.

go fetch(url)   // runs concurrently, costs a few KB, not an OS thread

A goroutine is a function running on its own, managed by Go instead of the . Go spreads thousands of over a few operating system . Each one starts with only a few kilobytes of memory, so 100,000 goroutines is normal. 100,000 operating system threads would overload the machine.

Starting tasks is the easy part. Making them work together is the hard part. Go's answer is the channel, which works like a pipe. One goroutine puts a value in, and another takes it out. Channels are safe to use from many goroutines at once.

func main() {
    urls := []string{"https://a.dev", "https://b.dev", "https://c.dev"}
    results := make(chan string)

    for _, u := range urls {
        go func(u string) {
            resp, err := http.Get(u)
            if err != nil {
                results <- u + ": error"
                return
            }
            resp.Body.Close()
            results <- u + ": " + resp.Status
        }(u)
    }

    for range urls {
        fmt.Println(<-results)   // receive blocks until a result arrives
    }
}

The three fetches run at the same time. The main function prints each result as soon as it arrives, in whatever order they finish. There are no locks and no shared variables.

THREE GOROUTINESfetch a.devfetch b.devfetch c.devresultschan string<-resultsmainprints each oneone result at a time,whichever is ready first
The program above. The channel is the only thing the four goroutines share.

Go has a saying for this.

Do not communicate by sharing memory. Share memory by communicating.

In many languages, several threads change one shared piece of data and use locks to take turns. In Go you usually send the data through a channel instead. Only one goroutine holds it at a time, so two goroutines can't change it at the same moment. When you do need a lock, sync.Mutex exists, and go run -race finds the places where two goroutines touch the same data without one.

The tooling is the other half of the language

Go comes with strong opinions, and they are built into its tools.

go fmt      one true formatting: tabs, brace style, all of it. Nobody argues.
go test     test runner built in; any TestXxx func in a _test.go file runs
go vet      catches suspicious code the compiler allows
go mod      dependency management; go.mod pins versions
go build    cross-compile with GOOS=linux GOARCH=arm64, no toolchain hunt

gofmt is worth a special mention. Every Go codebase is formatted the same way, so reading someone else's code feels familiar from the first line. Other communities still argue about formatting. Go settled it in 2009 by shipping one formatter with the language.

What Go deliberately leaves out

Knowing what is missing, and why, is half of understanding Go.

  • No inheritance. Embedding and do the same jobs without class hierarchies.
  • No exceptions. Every failure is handled in the code at the place it happens.
  • No manual memory management. A garbage collector frees memory that is no longer used, and it's tuned to pause the program only very briefly.
  • Generics arrived late, in 2022. Even now, most Go code uses plain interfaces first.

Each of these leaves the language with less power and makes the code easier to read. Code you wrote six months ago, or code a teammate wrote, looks like code you would write today. It's plain, and that's the point.

Next Steps

Start with the Tour of Go for the basics, then read Effective Go to learn the usual style, then write something real.

An (Hypertext Transfer Protocol) service is a good first project, because the net/http package in the standard library is good enough for production use.

http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "hello from a real web server")
})
http.ListenAndServe(":8080", nil)

That's a working web server in five lines, with no framework.

To sum up, Go is a small language with a large standard library. It's built on the belief that teams write software faster when the language is smaller.

Check yourself

3 questions · nothing is saved
  1. 1.You write var count int and never set it. What does count hold?
  2. 2.s := []int{10, 20, 30, 40, 50}, then t := s[1:4], then t[0] = 99. What is s[1] now?
  3. 3.How does a type come to implement an interface in Go?

References & Primary Sources

Official specifications, standards, and documentation cited in this post.

  1. [1]

    Official language specification covering syntax, types, and semantics

    SPECgo.dev
  2. [2]

    Official guide to writing clear, idiomatic Go code

    DOCSgo.dev
  3. [3]

    Guarantees on when reads of a variable observe values written by other goroutines

    SPECgo.dev

Who wrote this

Author profile and background

Takumi Yamada

Takumi Yamada

· Backend Engineer

Backend engineer building services, databases, Linux tooling, and NEGEN SYSTEMS. Writing about low-level mechanics, distributed systems, and real-world security.

End of post
NEGEN SYSTEMS
Receipt · post 15 of 31
Written
Mar 15, 2026
Length
2,202 words · 10 min
Built
…
Served by
…
Delivered
…
Over the wire
…
Go's share
…
Next in Programming Languages 101 · part 3 of 6

The Two Jobs of the Asterisk: Pointers in Go and C++

Pointers are often confusing, and much of the reason is one detail: the asterisk means two different things depending on where it is. Here's how to read it, in Go and in C++.

8 min read