Aide-mémoire Go
Une référence Go consultable et imprimable — structs, slices, maps, interfaces, encapsulation d'erreurs, goroutines, channels, génériques et la CLI go. Gratuit.
Basics
10package main
import ("fmt"; "os")
x := 42
var s string
const MaxRetries = 3
const (A = iota; B; C)
a, b = b, a
_, err := doWork()
fmt.Println("hi"); fmt.Printf("%v\n", x)
fmt.Sprintf("%s-%d", name, id)
Types, structs & methods
10type User struct { Name string; Age int }
u := User{Name: "Sam", Age: 30}
u.Name = "Alex"
func (u User) Label() string
func (u *User) Rename(n string)
func NewUser(n string) *User
type Admin struct { User; Level int }
type UserID int
Name string `json:"name,omitempty"`
p := &User{}; p.Name = "x"
Slices & maps
13s := []int{1, 2, 3}
s = make([]int, 0, 10)
s = append(s, 4, 5)
n := copy(dst, src)
s[1:3]
len(s), cap(s)
var s []int; s = append(s, 1)
m := map[string]int{"a": 1}
v, ok := m["key"]
delete(m, "key")
for k, v := range m { ... }
slices.Contains(s, 3)
slices.Sort(s); maps.Keys(m)
Control flow
10for i := 0; i < n; i++ { ... }
for i, v := range items { ... }
for cond { ... }
for { ... }
for i := range 10 { ... }
if err := load(); err != nil { ... }
switch status { case "on": ... default: ... }
switch { case n > 10: ... }
switch v := x.(type) { case int: ... }
outer: for { break outer }
Functions & defer
9func add(a, b int) int { return a + b }
func load() ([]byte, error)
func div(a, b int) (q int, err error)
func sum(ns ...int) int
defer f.Close()
defer mu.Unlock() // LIFO order
counter := func() int { n++; return n }
type Handler func(w, r)
apply(items, strings.ToUpper)
Interfaces & type assertions
10type Stringer interface { String() string }
// no "implements" keyword
io.Reader / io.Writer
var x any = 42
s, ok := x.(string)
switch v := x.(type) { case string: ... }
type ReadCloser interface { Reader; Closer }
func Save(w io.Writer, u User) error
func NewStore() *Store
var _ Stringer = (*User)(nil)
Error handling
10if err != nil { return err }
errors.New("not found")
fmt.Errorf("load %s: %w", path, err)
errors.Is(err, os.ErrNotExist)
var pe *fs.PathError; errors.As(err, &pe)
var ErrNotFound = errors.New("not found")
func (e *ValidationError) Error() string
errors.Join(err1, err2)
defer func() { recover() }()
panic("unreachable")
Goroutines & channels
12go work()
ch := make(chan int)
ch := make(chan int, 10)
ch <- v / v := <-ch
close(ch); for v := range ch { ... }
select { case v := <-a: ... case b <- x: ... }
var wg sync.WaitGroup; wg.Add(1); wg.Wait()
defer wg.Done()
for job := range jobs { results <- run(job) }
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
select { case <-ctx.Done(): return ctx.Err() }
var mu sync.Mutex; mu.Lock(); defer mu.Unlock()
Generics
9func Map[T, U any](s []T, f func(T) U) []U
func Keys[K comparable, V any](m map[K]V) []K
type Number interface { ~int | ~float64 }
func Sum[T Number](ns []T) T
type Stack[T any] struct { items []T }
s := Stack[int]{}
doubled := Map(nums, double)
func Min[T cmp.Ordered](a, b T) T
min(a, b), max(a, b)
Standard library gems
14strings.Split(s, ","); strings.Join(parts, "-")
strings.Contains, HasPrefix, TrimSpace
n, err := strconv.Atoi("42")
time.Now(); time.Since(start)
t.Format("2006-01-02 15:04")
time.Sleep(200 * time.Millisecond)
data, err := os.ReadFile("cfg.json")
os.WriteFile(path, data, 0o644)
os.Getenv("HOME"); filepath.Join(dir, f)
json.Marshal(v); json.Unmarshal(b, &v)
resp, err := http.Get(url); defer resp.Body.Close()
http.HandleFunc("/", h); http.ListenAndServe(":8080", nil)
slog.Info("started", "port", 8080)
sc := bufio.NewScanner(f); for sc.Scan()
Testing & benchmarks
11func TestAdd(t *testing.T) { ... }
t.Errorf("got %d, want %d", got, want)
t.Fatalf("setup failed: %v", err)
tests := []struct{ in, want int }{...}
t.Run(tc.name, func(t *testing.T) {...})
t.Helper()
t.Parallel()
func BenchmarkAdd(b *testing.B) { for range b.N { add(1, 2) } }
go test -bench=. -benchmem
go test -run TestAdd ./...
go test -cover ./...
Go CLI
11go mod init example.com/app
go mod tidy
go get github.com/pkg/x@latest
go run .
go build ./...
go test ./...
go vet ./...
gofmt -w .
go install golang.org/x/tools/...@latest
GOOS=linux GOARCH=amd64 go build
go doc strings.Split
Aucune entrée ne correspond à « :q ».
À propos de Aide-mémoire Go
Cet aide-mémoire Go condense le Go idiomatique en une seule page consultable : bases, types, structs et méthodes, slices et maps, contrôle de flux, fonctions et defer, interfaces et assertions de type, gestion des erreurs, goroutines et channels, génériques, joyaux de la bibliothèque standard, tests et benchmarks, et la ligne de commande go.
Il se concentre sur les choses que les développeurs Go recherchent plutôt que mémorisent — l'astuce exacte de slice pour supprimer un élément, comment errors.Is et errors.As diffèrent, l'instruction select avec un timeout, un test piloté par table, ou quelle commande go exécute quoi — avec une courte explication sur chaque ligne.
La fiche est gratuite et côté client : filtrez les lignes en direct avec la barre de recherche, sautez entre les sections avec le sommaire épinglé, copiez n'importe quel extrait d'un clic et imprimez la page comme référence pendant que vous codez.
Comment utiliser Aide-mémoire Go
- Parcourez les sections, des Bases et Slices et maps aux Goroutines et channels jusqu'à la CLI Go.
- Recherchez un mot-clé comme channel, defer ou errors.Is pour filtrer chaque ligne en direct.
- Sautez aux Interfaces ou aux Génériques quand vous avez besoin de la syntaxe de type plutôt que d'une commande.
- Cliquez sur un extrait ou son icône de copie pour copier le code Go dans votre presse-papiers.
- Imprimez la fiche pour une référence Go hors ligne.