Go Cheatsheet - Go Syntax & Concurrency Reference

All essential Go commands organized by use case, with 44+ entries you can copy and run directly. Find the right command fast when you need it.

Languages·44 commands·Last updated 2026-07-21
Back to Languages

Variables & Constants 7

var name string = "value"
显式Declarevariable
name := "value"
短variableDeclare(自动infertype)
const Pi = 3.14
Declareconstant
var (name string; age int)
batchDeclarevariable
var arr [5]int
Declarearray
slice := []int{1, 2, 3}
Declareslice
m := map[string]int{"a": 1}
Declare map

Control Flow 8

if condition { } else { }
if 语句
if err := fn(); err != nil { }
if 带初始化语句
switch x { case 1: case 2: default: }
switch 语句
for i := 0; i < 10; i++ { }
for loop
for condition { }
while 风格loop
for { }
无限loop
for i, v := range slice { }
iterateslice/array
for k, v := range map { }
iterate map

Functions 6

func add(a, b int) int { return a + b }
普通function
func swap(a, b int) (int, int)
多return value
func sum(nums ...int) int
可变Options
defer fn()
延迟Execute(functionDeactivate时Execute)
panic("error")
throw恐慌(程序崩溃)
recover()
catch恐慌(在 defer 中使用)

Struct & Method 5

type User struct { Name string; Age int }
定义struct
u := User{Name: "tom", Age: 20}
Createstruct实例
func (u User) String() string
值接收者method
func (u *User) SetName(n string)
指针接收者method
u := &User{}
Createstruct指针

Interface 5

type Reader interface { Read(p []byte) (int, error) }
定义interface
var r Reader = &File{}
interface实现(隐式,无需 implements)
type Empty interface{}
空interface(可存储任意type)
v, ok := i.(string)
type断言
switch v := i.(type) { }
type选择

Concurrency 8

go fn()
Start goroutine
ch := make(chan int)
Create无buffered channel
ch := make(chan int, 10)
Create有buffered channel
ch <- value
发送值到 channel
value := <-ch
从 channel 接收值
close(ch)
Close channel
select { case <-ch1: case <-ch2: }
多路复用
var wg sync.WaitGroup
await组,await多个 goroutine

Error Handling 5

if err != nil { return err }
stderrCheck
type MyError struct { msg string }
自定义错误type
func (e *MyError) Error() string
实现 error interface
errors.New("message")
Create错误
fmt.Errorf("failed: %w", err)
package装错误(Go 1.13+)

💡 Tips

  • Go 的错误处理是显式的,每个可能返回 error 的function都要Check err != nil。
  • goroutine 非常轻量(几 KB),可以轻松Create数十万个。
  • channel 是 goroutine 之间通信的主要方式,遵循 "不要通过共享Memory通信,而要通过通信共享Memory"。

Official References

Commands are compiled from the official docs below. Click to verify the latest usage.

Maintained by LaoHand

Publicly updated on Jul 21, 2026, continuously proofread against official docs.

Found an error? Report it

Wrong command or description? Open an issue to help us fix it.

Found an error? Report it