Short declaration with type inference (inside functions)
const Pi = 3.14159
Constant
n, err := strconv.Atoi("42")
Convert a string to an int
float64(x)
Explicit type conversion
Control Flow
if v, ok := m["k"]; ok { }
if with an init statement
for i := 0; i < 10; i++ { }
Counting loop
for i, v := range items { }
Iterate a slice with index and value
for cond { }
While-style loop
switch day { case "Sat", "Sun": ... default: ... }
Switch (no implicit fallthrough)
Slices & Maps
nums := []int{1, 2, 3}
Slice literal
nums = append(nums, 4)
Append (always reassign the result)
nums[1:3]
Sub-slice (shares the backing array)
ages := map[string]int{"ada": 36}
Map literal
v, ok := ages["bob"]
Comma-ok lookup
delete(ages, "ada")
Remove a key
Functions & Errors
func div(a, b float64) (float64, error) { }
Multiple return values
if err != nil { return err }
Check and propagate an error
fmt.Errorf("load config: %w", err)
Wrap an error with context
errors.Is(err, os.ErrNotExist)
Check for a wrapped error
defer f.Close()
Run when the function returns
Structs, Methods & Interfaces
type User struct { Name string; Age int }
Struct type
func (u *User) Birthday() { u.Age++ }
Method with a pointer receiver
type Shape interface { Area() float64 }
Interface (satisfied implicitly)
s, ok := v.(Circle)
Type assertion
func Max[T cmp.Ordered](a, b T) T { }
Generic function
Concurrency
go work()
Start a goroutine
ch := make(chan int, 10)
Buffered channel
ch <- v / v := <-ch
Send / receive
select { case v := <-ch: ... case <-time.After(time.Second): ... }
Wait on several channel operations
var wg sync.WaitGroup; wg.Add(1); defer wg.Done(); wg.Wait()
Wait for goroutines to finish
Tooling
go mod init example.com/app
Start a new module
go run .
Compile and run
go build -o app
Build a native binary
go test ./... -race -cover
Run all tests with the race detector
gofmt -w . / go vet ./...
Format and statically check code
Cookies & your privacy
We use essential cookies to keep this site working and secure.
With your permission, we'd also like to use Google Analytics cookies to understand site traffic.
We don't use advertising or social media tracking cookies, and we honor Global Privacy Control (GPC) browser signals.
Learn more in our Privacy Policy.
Your browser is sending a GPC signal, so analytics stays off even if you accept.