یک مرجع Go قابل‌جستجو و قابل‌چاپ: struct ها، slice ها، map ها، interface ها، wrap کردن خطا، goroutine ها، channel ها، generic ها و Go CLI. رایگان.

Basics

10
package main
Executable entry package
import ("fmt"; "os")
Import standard packages
x := 42
Short declare (inside funcs only)
var s string
Zero value: "" (0, nil, false)
const MaxRetries = 3
Typed or untyped constant
const (A = iota; B; C)
Auto-incrementing enum values
a, b = b, a
Multiple assignment / swap
_, err := doWork()
Blank identifier discards values
fmt.Println("hi"); fmt.Printf("%v\n", x)
Print values (%v = default)
fmt.Sprintf("%s-%d", name, id)
Format into a string

Types, structs & methods

10
type User struct { Name string; Age int }
Struct definition
u := User{Name: "Sam", Age: 30}
Struct literal (named fields)
u.Name = "Alex"
Field access / mutation
func (u User) Label() string
Value receiver (reads only)
func (u *User) Rename(n string)
Pointer receiver (mutates)
func NewUser(n string) *User
Constructor function idiom
type Admin struct { User; Level int }
Embedding: fields promoted
type UserID int
Named type (own method set)
Name string `json:"name,omitempty"`
Struct tag for encoding
p := &User{}; p.Name = "x"
Auto-deref through pointers

Slices & maps

13
s := []int{1, 2, 3}
Slice literal
s = make([]int, 0, 10)
Empty slice with capacity 10
s = append(s, 4, 5)
Append (reassign the result)
n := copy(dst, src)
Copy elements between slices
s[1:3]
Sub-slice (shares the array)
len(s), cap(s)
Length and capacity
var s []int; s = append(s, 1)
Appending to nil is fine
m := map[string]int{"a": 1}
Map literal
v, ok := m["key"]
Lookup with existence check
delete(m, "key")
Remove a key
for k, v := range m { ... }
Iterate (order is random)
slices.Contains(s, 3)
Search helper (Go 1.21+)
slices.Sort(s); maps.Keys(m)
slices / maps packages

Control flow

10
for i := 0; i < n; i++ { ... }
Classic for (the only loop)
for i, v := range items { ... }
Index + value iteration
for cond { ... }
While-style loop
for { ... }
Infinite loop (break to exit)
for i := range 10 { ... }
Range over int (Go 1.22+)
if err := load(); err != nil { ... }
If with init statement
switch status { case "on": ... default: ... }
No fallthrough by default
switch { case n > 10: ... }
Condition-less switch chain
switch v := x.(type) { case int: ... }
Type switch
outer: for { break outer }
Labeled break / continue

Functions & defer

9
func add(a, b int) int { return a + b }
Basic function
func load() ([]byte, error)
Multiple return values
func div(a, b int) (q int, err error)
Named return values
func sum(ns ...int) int
Variadic; call sum(s...)
defer f.Close()
Run at function exit
defer mu.Unlock() // LIFO order
Multiple defers run in reverse
counter := func() int { n++; return n }
Closure captures variables
type Handler func(w, r)
Function type declaration
apply(items, strings.ToUpper)
Functions are first-class values

Interfaces & type assertions

10
type Stringer interface { String() string }
Interface: a method set
// no "implements" keyword
Satisfaction is implicit
io.Reader / io.Writer
The ubiquitous stream duo
var x any = 42
any = interface{} (anything)
s, ok := x.(string)
Type assertion (safe form)
switch v := x.(type) { case string: ... }
Branch by dynamic type
type ReadCloser interface { Reader; Closer }
Interface embedding
func Save(w io.Writer, u User) error
Accept interfaces...
func NewStore() *Store
...return concrete structs
var _ Stringer = (*User)(nil)
Compile-time conformance check

Error handling

10
if err != nil { return err }
The fundamental pattern
errors.New("not found")
Simple error value
fmt.Errorf("load %s: %w", path, err)
Wrap with context (%w)
errors.Is(err, os.ErrNotExist)
Match a sentinel in the chain
var pe *fs.PathError; errors.As(err, &pe)
Extract a typed error
var ErrNotFound = errors.New("not found")
Exported sentinel error
func (e *ValidationError) Error() string
Custom error type
errors.Join(err1, err2)
Combine multiple errors
defer func() { recover() }()
Recover from a panic
panic("unreachable")
Only for programmer errors

Goroutines & channels

12
go work()
Start a goroutine
ch := make(chan int)
Unbuffered (synchronous) channel
ch := make(chan int, 10)
Buffered channel
ch <- v / v := <-ch
Send / receive
close(ch); for v := range ch { ... }
Drain until closed
select { case v := <-a: ... case b <- x: ... }
Wait on multiple channels
var wg sync.WaitGroup; wg.Add(1); wg.Wait()
Wait for goroutines
defer wg.Done()
Signal completion
for job := range jobs { results <- run(job) }
Worker pool body
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
Deadline for downstream work
select { case <-ctx.Done(): return ctx.Err() }
Abort on cancellation
var mu sync.Mutex; mu.Lock(); defer mu.Unlock()
Guard shared state

Generics

9
func Map[T, U any](s []T, f func(T) U) []U
Generic function
func Keys[K comparable, V any](m map[K]V) []K
comparable: map-key types
type Number interface { ~int | ~float64 }
Union constraint (~ = derived)
func Sum[T Number](ns []T) T
Use a custom constraint
type Stack[T any] struct { items []T }
Generic type
s := Stack[int]{}
Explicit instantiation
doubled := Map(nums, double)
Type args usually inferred
func Min[T cmp.Ordered](a, b T) T
cmp.Ordered: < > comparable
min(a, b), max(a, b)
Builtins since Go 1.21

Standard library gems

14
strings.Split(s, ","); strings.Join(parts, "-")
Split and join
strings.Contains, HasPrefix, TrimSpace
Everyday string helpers
n, err := strconv.Atoi("42")
String → int (Itoa reverses)
time.Now(); time.Since(start)
Current time and elapsed
t.Format("2006-01-02 15:04")
Reference-date layout
time.Sleep(200 * time.Millisecond)
Pause the goroutine
data, err := os.ReadFile("cfg.json")
Read a whole file
os.WriteFile(path, data, 0o644)
Write a file with perms
os.Getenv("HOME"); filepath.Join(dir, f)
Env vars and safe paths
json.Marshal(v); json.Unmarshal(b, &v)
JSON encode / decode
resp, err := http.Get(url); defer resp.Body.Close()
HTTP client call
http.HandleFunc("/", h); http.ListenAndServe(":8080", nil)
Minimal HTTP server
slog.Info("started", "port", 8080)
Structured logging (1.21+)
sc := bufio.NewScanner(f); for sc.Scan()
Read input line by line

Testing & benchmarks

11
func TestAdd(t *testing.T) { ... }
Test in *_test.go
t.Errorf("got %d, want %d", got, want)
Fail but keep running
t.Fatalf("setup failed: %v", err)
Fail and stop this test
tests := []struct{ in, want int }{...}
Table-driven test data
t.Run(tc.name, func(t *testing.T) {...})
Named subtests
t.Helper()
Blame the caller in failures
t.Parallel()
Run this test concurrently
func BenchmarkAdd(b *testing.B) { for range b.N { add(1, 2) } }
Benchmark loop
go test -bench=. -benchmem
Run benchmarks + allocations
go test -run TestAdd ./...
Run tests matching a pattern
go test -cover ./...
Coverage summary

Go CLI

11
go mod init example.com/app
Start a new module
go mod tidy
Sync go.mod with imports
go get github.com/pkg/x@latest
Add / upgrade a dependency
go run .
Compile and run in one step
go build ./...
Build all packages
go test ./...
Test the whole module
go vet ./...
Static analysis for bugs
gofmt -w .
Format all source files
go install golang.org/x/tools/...@latest
Install a tool binary
GOOS=linux GOARCH=amd64 go build
Cross-compile
go doc strings.Split
Read docs in the terminal

هیچ موردی با «:q» مطابقت ندارد.


درباره چیت شیت Go

این تقلب‌نامه Go، Go ایدیوماتیک را در یک صفحه قابل‌جستجو فشرده می‌کند: مبانی، انواع، struct ها و متدها، slice ها و map ها، جریان کنترل، توابع و defer، interface ها و type assertion ها، مدیریت خطا، goroutine ها و channel ها، generic ها، جواهرات کتابخانه استاندارد، تست و benchmark، و خط‌فرمان go.

بر چیزهایی تمرکز می‌کند که توسعه‌دهنده‌های Go جستجو می‌کنند نه حفظ می‌کنند: ترفند دقیق slice برای حذف یک عنصر، تفاوت errors.Is و errors.As، عبارت select با یک timeout، یک تست table-driven، یا اینکه کدام دستور go چه کاری انجام می‌دهد، با یک توضیح کوتاه در هر ردیف.

این برگه رایگان و سمت‌کلاینت است: ردیف‌ها را زنده با جعبه جستجو فیلتر کنید، با فهرست مطالب چسبان بین بخش‌ها بپرید، هر قطعه‌کد را با یک کلیک کپی کنید و صفحه را برای مرجع حین کدنویسی چاپ کنید.

نحوه استفاده از چیت شیت Go

  1. بخش‌ها را مرور کنید، از Basics و Slices & maps تا Goroutines & channels و در نهایت Go CLI.
  2. برای فیلتر زنده هر ردیف، کلیدواژه‌ای مانند channel، defer یا errors.Is را جستجو کنید.
  3. وقتی به نحو نوع نیاز دارید نه یک دستور، به Interfaces یا Generics بروید.
  4. روی یک قطعه‌کد یا آیکون کپی آن کلیک کنید تا کد Go در کلیپ‌بورد شما کپی شود.
  5. برگه را برای یک مرجع آفلاین Go چاپ کنید.

سوالات متداول

دوازده بخش: مبانی، انواع و struct ها، slice ها و map ها، جریان کنترل، توابع و defer، interface ها و type assertion ها، مدیریت خطا، goroutine ها و channel ها، generic ها، نکات برجسته کتابخانه استاندارد، تست و benchmark، و Go CLI.

بله. یک بخش اختصاصی goroutine ها، channel های buffered و unbuffered، select با timeout، WaitGroup، Mutex و لغو context را پوشش می‌دهد.

بله: پارامترهای نوع، محدودیت‌ها، محدودیت‌های comparable و any، و توابع و انواع generic هرکدام ردیف مخصوص خودشان را دارند.

بله. روی هر قطعه‌کد یا آیکون کپی که با هاور ظاهر می‌شود کلیک کنید و با یک تأیید کوتاه در کلیپ‌بورد شما قرار می‌گیرد.

بله، کاملاً رایگان: قابل‌جستجو، قابل‌چاپ و بدون ثبت‌نام در مرورگر شما نمایش داده می‌شود.

اشتراک‌گذاری

جستجوهای پرطرفدار
چیت شیت go چیت شیت golang مرجع نحو go slice و map در go goroutine و channel مدیریت خطا در go دستورات cli در go
به کمک نیاز دارید؟
با این ابزار مشکلی پیدا کردید؟ به تیم ما اطلاع دهید.
گزارش مشکل

این ابزار رایگان را به وب‌سایت خود اضافه کنید: کد زیر را کپی و جای‌گذاری کنید.