Thuta Learning
Go
BasicProgrammingBeginner

What is Go?

GoLesson 220 min

What you'll walk away with

  • Explain the difference between compiled and interpreted languages from a deployment point of view
  • Say what go run and go build do behind the scenes
  • Understand why Go treats unused imports and unused variables as errors
  • Know that Go uses structs, methods and error values instead of classes and exceptions

Explain it simply

What is Go, simply?

Go is a compiled programming language that started at Google. 'Compiled' means that before your code runs, a compiler translates it into machine code the computer understands. It is like handing someone a cooked meal instead of a recipe: the person eating it does not need to know how to cook.

Go aims to be simple, fast and good at doing many things at once. That is why server-side applications written in Go are quick and stable.

Problem → Why → Solution

The problem: it runs on my laptop but not on the server

You write a report script in an interpreted language such as Python, and it works fine on your laptop. Then you copy it to a server, run it, and it crashes immediately because a package is missing. The server needed the right interpreter version and the right libraries installed first.

With ten servers or a fleet of containers the problem grows. Keeping the runtime and dependencies identical on every machine becomes a job of its own.

terminal
# On your laptop
$ python3 report.py
Report ready

# On the server
$ python3 report.py
ModuleNotFoundError: No module named 'requests'

How Go avoids this

An interpreted program needs the interpreter and its libraries on every machine it runs on. With Go, `go build` puts your code, the packages it uses and the Go runtime itself into one executable file. You copy that file to a server with the same operating system and CPU type and run it; the server does not need Go installed.

Core concept: the choices behind Go's design

Go was designed at Google to deal with slow builds of very large code bases, languages that had grown complicated, and software that could not make full use of multicore CPUs. As a result, almost every feature of Go exists for a specific reason.

Fast compiles, one binary

`go run hello.go` compiles the file into a temporary executable and runs it straight away. `go build` keeps the executable in your folder so you can run it again later.

Static typing

Every variable has a type, and the compiler rejects mismatches before anything runs. Thanks to `:=` you rarely have to spell the type out yourself.

A strict compiler

An imported package you never use, or a local variable you declare and never use, is a compile error, not a warning. It feels strict at first, but it keeps large projects clean and keeps builds fast.

Garbage collection and goroutines

The runtime reclaims memory automatically, and the `go` keyword runs a function as a goroutine, concurrently with the rest of the program.

text
From source to a file you can ship
----------------------------------
hello.go --go build--> hello (hello.exe on Windows) --copy--> server
 source    compile +    one file: your code,             runs with
           type check   packages and the Go runtime      no Go installed

Some features are left out on purpose. There are no classes or inheritance; Go uses structs and methods. There are no exceptions; functions return errors as ordinary values. The language is small, with just 25 keywords, and its whole specification can be read in an afternoon.

The language is small, but its standard library is large. Packages such as `net/http` for HTTP servers, `encoding/json` for JSON, `strings` for text and `testing` for tests ship with Go, so a simple service can be written without any third-party library. On the tooling side, the single `go` command builds, runs, tests, formats (`go fmt`), checks for suspicious code (`go vet`) and manages dependencies (`go mod`).

Mental model: the life of a Go program
  1. Write a .go file
  2. Compiler checks types and imports
  3. One executable comes out
  4. The OS runs it directly

No interpreter is involved, so the machine that runs the executable does not need Go installed.

General pattern: a program with grouped imports

go
package main

import (
    "packageone"
    "packagetwo"
)

func main() {
    packageone.Function(argument)
}

When you use more than one package, group the imports in parentheses, one per line. Every imported package must be used at least once or the file does not compile. You call a package's function as `packagename.FunctionName`.

Reading Hello, Go! piece by piece

This program prints only one line, but it contains every part a Go program needs. Save it as `hello.go` and run it with `go run hello.go`. Then build an executable with `go build hello.go` and run that file directly.

go
package main

import "fmt"

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

Code breakdown

  1. Package clausepackage main

    This says which package the file's code belongs to. The name `main` is special: the compiler builds this package into an executable program.

  2. Importimport "fmt"

    This brings in the `fmt` (format) package from the standard library, which holds the functions that print text. Keep this line but never use `fmt` and you get `"fmt" imported and not used`.

  3. Entry pointfunc main() {

    This is where the program begins. `main` takes no parameters and returns nothing, and when it finishes, the whole program ends.

  4. Calling an exported functionfmt.Println("Hello, Go!")

    This calls `Println` from the `fmt` package, printing the text followed by a newline. `Println` starts with a capital P, which makes it an exported name usable from outside its package.

You should see
Hello, Go!

How Go compares with other languages

Go is not better than every language at everything, but it differs clearly in how a program runs and how you ship it.

LanguageHow it runsWhat the server needs
GoCompiled to machine codeJust the executable file
PythonRun by an interpreterThe interpreter plus packages
JavaCompiled to bytecode, run by the JVMA JVM (Java runtime)
CCompiled to machine codeThe executable (memory managed by hand)

In real projects

What these design choices buy you in real projects

One executable means small container images: many Go services ship as a single binary on a base image with no language runtime at all. For command-line tools, users simply download one file and run it. Cross-compiling is easy too: set the `GOOS` and `GOARCH` environment variables and you can build a Linux server binary from a Windows laptop.

The strict compiler pays off in team work as well. Reviewers never have to hunt for stale imports or forgotten variables, because the compiler has already refused them. And since `gofmt` formats everyone's code the same way, even a very large project stays easy to read. Fast compiles keep the edit-and-test loop short, which matters when a test suite runs on every commit.

Common mistakes

Common mistakes

1. Not saving the file with a .go extension

Editors such as Notepad can quietly save `hello.go.txt`. `go run` only treats files ending in `.go` as Go source; anything else is taken as a package name and fails. Turn on file extensions in your file explorer and check the name.

2. Importing a package and not using it

Import `"os"` for some debugging, delete the code that used it, and you get `"os" imported and not used`. Delete the import line too, or let your editor's Go extension (`gopls`) fix imports automatically on save.

3. Looking for classes and try/catch

People coming from Java or Python often look for the `class` keyword and `try`/`catch`. Go has neither. Data goes in structs, behavior goes in methods, and errors are checked with `if err != nil`; the Structs, Methods and Error Handling lessons cover each one.

Best practices

Best practices

  • Try every new program with `go run` first, and build an executable with `go build` only when you need to ship it.
  • Install the Go extension in your editor so `gofmt` and import fixes run automatically on every save.
  • Before searching for a third-party package, check whether the standard library already has what you need.

Mini challenge

Mini challenge: a Go fact card

Write a program that prints a small fact card about Go. It must import two packages and use both of them.

  • Import `fmt` and `strings` as a grouped import
  • Draw a line with `strings.Repeat`
  • Print the language name, whether it is compiled (true) and its keyword count (25)
  • After it runs, temporarily delete one use of a package and note the error you get
factcard.go
package main

// TODO: grouped import of fmt and strings

func main() {
    // TODO: build a line of 20 "-" characters with strings.Repeat
    // TODO: print the line, then three facts, then the line again
}

Expected: -------------------- Language: Go Compiled: true Keywords: 25 --------------------

Show hint

`strings.Repeat("-", 20)` returns a string of twenty dashes. `fmt.Println("Compiled:", true)` prints a boolean directly.

Show solution
factcard.go
package main

import (
    "fmt"
    "strings"
)

func main() {
    line := strings.Repeat("-", 20)

    fmt.Println(line)
    fmt.Println("Language:", "Go")
    fmt.Println("Compiled:", true)
    fmt.Println("Keywords:", 25)
    fmt.Println(line)
}

Quick quiz 1 / 3

You add import "os" but never use os anywhere. What happens?

Quick quiz 2 / 3

You build hello.exe with go build on Windows. What happens when you run it on another Windows PC without Go?

Quick quiz 3 / 3

What does go run hello.go do?

What to remember

  • Go compiles to machine code and produces one executable containing your code, its packages and the runtime.
  • go run compiles and runs in one step; go build keeps the executable.
  • Unused imports and unused local variables are compile errors.
  • Go has no classes or exceptions; it uses structs, methods and error values.

Go release history — Go

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

What is Go? | Thuta Learning