Back to Notes

Go Basics

Hello World

package main

import "fmt"

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

Every Go program starts in package main. Execution begins in func main().


Packages

Every Go program is made of packages. By convention, the package name matches the last element of the import path — math/rand contains files that begin with package rand.

import (
	"fmt"
	"math/rand"
)

func main() {
	fmt.Println("My favorite number is", rand.Intn(10))
}

Imports

Use the factored import statement (preferred style):

import (
	"fmt"
	"math"
)

Single import is also valid: import "fmt"


Exported Names

A name is exported if it begins with a capital letter.

  • Pizza, Pi → exported ✅
  • pizza, pi → unexported ❌

When importing a package you can only use its exported names.

fmt.Println(math.Pi)   // ✅
fmt.Println(math.pi)   // ❌ compile error: undefined

Comments

// Single-line comment

/*
   Multi-line comment
*/

Dependency Tracking

External packages are tracked via go.mod:

go mod init <module-path>   # creates go.mod

go.sum contains cryptographic hashes of all direct + indirect dependencies for integrity verification:

rsc.io/quote v1.5.2 h1:w5fcysjrx7yqtD/aO+QwRjYZOKnaM9Uh2b40tElTs3Y=
rsc.io/quote v1.5.2/go.mod h1:LzX7hefJvL54yjefDEDHNONDjII0t9xZLPXsUe+TKr0=

Each line: <module-path> <version> <hash> (hash = algo:base64)

go mod tidy   # add missing hashes, remove unused ones

External packages are found at pkg.go.dev.


Compilation

Go is compiled. Two kinds of errors:

KindWhenImpact
Compilation errorAt build timeBinary not created — can't ship broken code
Runtime errorDuring executionCan crash or misbehave in production

String Formatting

FunctionUse
fmt.Printf(...)Print formatted string to stdout
fmt.Sprintf(...)Return formatted string
fmt.Println(...)Print with newline

Format Verbs

VerbTypeExample output
%vAny (default)42, true, hello
%TType nameint, string
%sStringhello
%dInteger42
%fFloat10.523000
%.2fFloat (2 dp)10.52
%qQuoted string"hello"
%bBinary101010
s := fmt.Sprintf("I am %d years old and %.2f meters tall", 25, 1.75)
// "I am 25 years old and 1.75 meters tall"