Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Go (Golang) Cheat Sheet

Project and tools

// new module, run, build, test, format
go mod init example.com/app
go run .
go build -o app
go test ./...
go fmt ./... && go vet ./...
go get github.com/gin-gonic/gin

Basics

var x int = 5; y := 10; const Pi = 3.14
fmt.Println(a, b); fmt.Printf("%d %s %v %.2f\n", n, s, v, f)
s := fmt.Sprintf("id-%03d", 7)
n, err := strconv.Atoi("42"); str := strconv.Itoa(42)

Control flow

if v, ok := m[k]; ok { }
for i := 0; i < n; i++ { }
for cond { }
for i, v := range slice { }
switch x { case 1, 2: default: }

Slices and maps

s := []int{1, 2}; s = append(s, 3); s[1:3]; len(s); cap(s)
s := make([]int, n)
copy(dst, src)
sort.Ints(s); sort.Slice(p, func(i, j int) bool { return p[i].Age < p[j].Age })
m := map[string]int{}; m["a"] = 1; delete(m, "a"); v, ok := m["a"]

Structs, methods, interfaces

type User struct { Name string; Age int }
func (u *User) Birthday() { u.Age++ }
type Speaker interface { Speak() string }
u := &User{Name: "Asha"}

Errors

if err != nil { return fmt.Errorf("load config: %w", err) }
errors.Is(err, ErrNotFound); errors.New("msg")
defer f.Close()

Concurrency

go work()
ch := make(chan int, 10); ch <- 1; v := <-ch; close(ch)
var wg sync.WaitGroup; wg.Add(1); defer wg.Done(); wg.Wait()
var mu sync.Mutex; mu.Lock(); mu.Unlock()
select { case v := <-ch: case <-time.After(time.Second): }

Full Go (Golang) documentation