Go — Basics
Go — Basics
Section titled “Go — Basics”Language essentials
Section titled “Language essentials”- Static typed, compiled, garbage collected, opinionated formatting (
gofmt). - Zero values: every type has one —
0,"",false,nil. No null vs undefined confusion. - No classes — structs + methods + interfaces. No inheritance, only composition.
- Multiple return values: idiomatic for
(value, err). - Capitalization = export.
Fooexported,foopackage-private.
- Primitives:
int,int64,uint,float64,bool,string,byte(= uint8),rune(= int32). - Composite: array (fixed size), slice (dynamic), map, struct, channel, function, interface, pointer.
stringis immutable byte sequence; range over string yields runes (UTF-8 decoded).
Slices vs arrays
Section titled “Slices vs arrays”- Array:
[3]int— fixed size, value type. - Slice:
[]int— header (ptr, len, cap). Reference type.appendmay reallocate. make([]int, len, cap).- Slicing shares underlying array — beware of memory retention.
map[K]V. Not safe for concurrent write — usesync.Mapor mutex.- Iteration order is randomized.
- Zero value of map is nil — must
make()before write.
Structs and methods
Section titled “Structs and methods”type User struct { ID string Email string}
func (u User) IsAdmin() bool { return u.ID == "admin" } // value receiverfunc (u *User) Rename(n string) { u.Email = n } // pointer receiver- Use pointer receiver if method mutates or struct is large.
- Embedding for composition:
type Admin struct { User; Permissions []string }.
Interfaces
Section titled “Interfaces”- Implicit satisfaction — no
implements. - Empty interface
interface{}(oranysince 1.18) holds anything. - Small interfaces preferred (
io.Reader= single method).
Error handling
Section titled “Error handling”- No exceptions. Functions return
(T, error). Caller checks:if err != nil { return err }. - Wrap with
fmt.Errorf("ctx: %w", err). Unwrap witherrors.Is,errors.As. paniconly for unrecoverable;recoverinside deferred fn.
Goroutines & channels
Section titled “Goroutines & channels”go fn()— launch goroutine (lightweight, ~2KB stack, grows).- Channel: typed conduit.
ch := make(chan int, 5)(5 = buffer; 0 = unbuffered/sync). - Send:
ch <- v. Receive:v := <-ch. Close:close(ch). - Range until closed:
for v := range ch { ... }. - Select: multi-channel wait.
select {case v := <-ch1:case ch2 <- x:case <-time.After(1*time.Second):case <-ctx.Done():}sync primitives
Section titled “sync primitives”sync.Mutex(write lock),sync.RWMutex(read-write).sync.WaitGroup— wait for N goroutines.sync.Once— run-once init.sync.Pool— object pool, GC-friendly.sync/atomic— lock-free counters / loads / stores.
context
Section titled “context”context.Contextpropagates cancellation, deadline, request values.context.Background()root,context.TODO()placeholder.context.WithCancel,WithTimeout,WithDeadline,WithValue.- Always pass as first arg:
func F(ctx context.Context, ...). - Always
defer cancel().
Generics (1.18+)
Section titled “Generics (1.18+)”func Map[T, U any](xs []T, f func(T) U) []U { out := make([]U, len(xs)) for i, x := range xs { out[i] = f(x) } return out}- Type parameters with constraints (
comparable,~int, custom interface).
Modules / build
Section titled “Modules / build”go mod init,go get,go mod tidy.go build,go run,go test,go vet,go fmt.- Cross-compile:
GOOS=linux GOARCH=amd64 go build. - Build tags:
//go:build linux.
Standard lib heavyweights
Section titled “Standard lib heavyweights”net/http,encoding/json,database/sql,os,io,fmt,time,regexp,sort,strings,bytes,bufio.