Build robust Go programs through idiomatic error handling: error interface, Sentinel Errors, wrapping with %w, Custom Error Types, panic/recover, and HTTP mapping.
In Go there are two main ways plus const. The short form :=
is the Go idiom — it takes the type automatically from the right-hand value.
package main
import "fmt"
func main() {
var name string = "ana" // explicit: type + value
var city string // explicit, empty value ""
age := 30 // short form: type inferred (int)
const pi = 3.14159 // constants: never changed, never deleted
fmt.Println(name, city, age, pi)
}
The basic types
Go is statically typed: every variable has a fixed type.
| Type | Examples | Note |
|---|---|---|
int, int32, int64 | 42 | architecture-dependent vs. fixed width |
float64, float32 | 3.14 | float64 is the default |
bool | true, false | |
string | "hello" | immutable, UTF-8 |
byte, rune | 'a', 'ä' | rune = Unicode character (int32) |
The short form := is shorter, and the type sits right next to the visible
value. You need var when declaring without an initial value (e.g.
var list []string). Important: := only works inside functions. At
package level you write var.
var counter int // package level: only var allowed
func main() {
x := 10 // declare anew
x = x + 1 // assign, no := (x already exists)
// x := 20 // ERROR: no new variables on left side of :=
_ = x
}
The blank variable _ deliberately discards values — Go forces you to use
everything you declare.
⚠ Common mistake:
x := 20inside an inner block (e.g. the body of anif) creates a new variable and shadows the outer one — the compiler does not warn you, and the assignment never reaches the outside. When the variable already exists, always write=instead of:=.
Check: Why does this line fail: x := 1; x := 2 ?
Answer: Because := only declares once per variable in the same scope — afterwards assign with =
:= declares and initializes. Once the variable exists you use = (assignment). Points 2–4 are nonsense in Go.
if can run an initialization first — the pattern you find everywhere in Go
source code:
package main
import (
"fmt"
"os"
)
func main() {
if len(os.Args) < 2 {
fmt.Println("Please provide an argument")
return
}
name := os.Args[1]
// Go idiom: statement ; condition
if msg := "Hello " + name; len(name) < 3 {
fmt.Println(msg, "(short name)")
} else {
fmt.Println(msg)
}
}
No while, no do-while. Every loop is for — in three variants:
// 1) Classic (like C)
for i := 0; i < 5; i++ {
fmt.Println(i)
}
// 2) As while
n := 3
for n > 0 {
n--
}
// 3) Range over slices, maps, strings (lesson 9)
for i, v := range []string{"a", "b", "c"} {
fmt.Println(i, v)
}
Go-switch has no fall-through: at the end of each case there is an
implicit break. A comma lists multiple cases, default is optional.
status := "open"
switch status {
case "open", "in progress":
fmt.Println("Active")
case "closed":
fmt.Println("Done")
default:
fmt.Println("Unknown")
}
Check: How do you write a while loop in Go?
Answer: for condition { ... }
There is only for. Without init and post statement it becomes the while variant. Anything else does not exist in Go.
Go functions can return several values. Combined with error as the
second return value you get the famous Go error pattern — explicit instead
of exceptions.
package main
import (
"fmt"
"strconv"
)
// Multiple returns: (result, error)
func parseAge(s string) (int, error) {
n, err := strconv.Atoi(s)
if err != nil {
return 0, fmt.Errorf("not a number: %q", s)
}
return n, nil
}
func main() {
age, err := parseAge("32")
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Age:", age)
// → Age: 32
}
Named return values
You can name return values and just write return; the variables are
created with their zero values.
func divide(a, b float64) (result float64, err error) {
if b == 0 {
err = fmt.Errorf("division by zero")
return
}
result = a / b
return
}
defer postpones a call to the end of the function. This puts the close
right next to the open — the most important Go pattern for files, connections,
locks.
import "os"
func readFile(path string) (string, error) {
f, err := os.Open(path)
if err != nil {
return "", err
}
defer f.Close() // runs at the end of the function — even on early return
buf := make([]byte, 1024)
n, _ := f.Read(buf)
return string(buf[:n]), nil
}
Check: What does defer f.Close() do?
Answer: It calls Close at the end of the function — even on early return
defer runs at function end (LIFO order) — written at the open site, guaranteed to run on error paths.
[]T is a slice: a window over an array that grows with append.
Literals, make, and range iteration cover 99 % of the work.
package main
import "fmt"
func main() {
// Literal
nums := []int{1, 2, 3}
// make: slice with room for 0 elements, capacity 10
items := make([]string, 0, 10)
items = append(items, "first")
// append grows automatically
for i := 4; i <= 6; i++ {
nums = append(nums, i)
}
// Slicing: [from, to) — half open
tail := nums[1:3] // [2 3]
// range: index + value
for i, v := range nums {
fmt.Println(i, v, cap(items))
}
_ = tail
}
Maps — the fast lookup
map[K]V is the associative store. The double-value idiom v, ok checks
whether a key exists — Go's answer to "key not found".
scores := map[string]int{"ana": 95}
scores["ben"] = 88
delete(scores, "ben")
val, ok := scores["ana"]
if !ok {
fmt.Println("missing")
}
fmt.Println("ana:", val)
⚠ Common mistake: A map declared with
var scores map[string]intisnil— the first write likescores["ben"] = 88crashes withpanic: assignment to entry in nil map. Reading, by contrast, is harmless and yields the zero value. Always create maps withmake(...)or a literal before filling them.
append can change the capacity — if you keep an old reference, it points
at the old memory.func main() {
a := []int{1, 2, 3}
b := a
b[0] = 99 // also changes a[0] — the slice shares the array
fmt.Println(a[0]) // 99
}
Check: What does the program print if you copy a slice and change one element?
Answer: The change also affects the original, because slices point at the same array
B is a copy of the slice structure (ptr, len, cap) but points at the same data. An element change hits both. Use copy() for independence.
A struct bundles fields. The type receives methods via a receiver —
that is Go's way of replacing classes: data and behaviour, without
inheritance.
package main
import "fmt"
type User struct {
Name string
Age int
}
// Value receiver: works on a copy
func (u User) Greeting() string {
return "Hello, " + u.Name
}
// Pointer receiver: modifies the original
func (u *User) Birthday() {
u.Age++
}
func main() {
u := User{Name: "ana", Age: 30}
fmt.Println(u.Greeting())
// → Hello, ana
u.Birthday()
fmt.Println(u.Age) // 31
}
Value vs. pointer receiver
| Receiver | Copy? | When |
|---|---|---|
func (u User) | yes (copy) | read-only or small values |
func (u *User) | no (original) | change state or large structs |
Rule of thumb: consistency — if one method takes a pointer, all methods of the type do, otherwise it gets confusing.
With String() string on a value receiver you override the default output
for fmt.Println — Go's counterpart to toString() without a class
hierarchy:
func (u User) String() string {
return fmt.Sprintf("%s (%d years)", u.Name, u.Age)
}
// fmt.Println(u) → ana (30 years)
Check: What is the difference between a value receiver and a pointer receiver?
Answer: A value receiver works on a copy; a pointer receiver can modify the original
Value = copy (read-only), pointer = original (mutation). For consistency pick one variant per type.
Course navigation: ← Module 1 · All 20 modules · Module 3 →