Go 치트시트
검색과 인쇄가 가능한 Go 참고자료입니다: 구조체, 슬라이스, 맵, 인터페이스, 에러 래핑, 고루틴, 채널, 제네릭, go CLI까지. 무료입니다.
Basics
10package 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
10type 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
13s := []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
10for 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
9func 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
10type 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
10if 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
12go 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
9func 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
14strings.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
11func 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
11go 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를 검색 가능한 한 페이지로 압축했습니다: 기초, 타입, 구조체와 메서드, 슬라이스와 맵, 제어 흐름, 함수와 defer, 인터페이스와 타입 단언, 오류 처리, 고루틴과 채널, 제네릭, 표준 라이브러리의 유용한 기능, 테스트와 벤치마크, 그리고 go 명령줄까지 다룹니다.
Go 개발자가 외우기보다는 찾아보는 것들에 초점을 맞춥니다: 요소를 삭제하는 정확한 슬라이스 기법, errors.Is와 errors.As의 차이, 타임아웃이 있는 select 문, 테이블 기반 테스트, 또는 어떤 go 명령이 무엇을 실행하는지 등을 각 행마다 짧은 설명과 함께 다룹니다.
이 시트는 무료이며 클라이언트 측에서 동작합니다: 검색창으로 실시간으로 행을 필터링하고, 고정된 목차로 섹션을 이동하고, 클릭 한 번으로 스니펫을 복사하고, 코딩하는 동안 참고할 수 있도록 페이지를 인쇄할 수 있습니다.
Go 치트시트 사용 방법
- 기초와 슬라이스 & 맵부터 고루틴 & 채널을 거쳐 Go CLI까지 섹션을 훑어보세요.
- channel, defer, errors.Is 같은 키워드를 검색해 모든 행을 실시간으로 필터링하세요.
- 명령이 아니라 타입 문법이 필요할 때는 인터페이스나 제네릭 섹션으로 이동하세요.
- 스니펫이나 복사 아이콘을 클릭해 Go 코드를 클립보드에 복사하세요.
- 오프라인 Go 참고자료로 시트를 인쇄하세요.
자주 묻는 질문
12개 섹션입니다: 기초, 타입과 구조체, 슬라이스와 맵, 제어 흐름, 함수와 defer, 인터페이스와 타입 단언, 오류 처리, 고루틴과 채널, 제네릭, 표준 라이브러리 하이라이트, 테스트와 벤치마크, go CLI입니다.
네. 전용 섹션에서 고루틴, 버퍼링 및 비버퍼링 채널, 타임아웃이 있는 select, WaitGroup, Mutex, context 취소를 다룹니다.
포함되어 있습니다: 타입 매개변수, 제약, comparable과 any 제약, 그리고 제네릭 함수와 타입이 각각 별도의 행으로 다뤄집니다.
네. 어떤 스니펫이든 클릭하거나 마우스오버 시 나타나는 복사 아이콘을 클릭하면 짧은 확인 메시지와 함께 클립보드에 저장됩니다.
네, 완전히 무료입니다: 검색과 인쇄가 가능하며 가입 없이 브라우저에서 렌더링됩니다.
인기 검색어
go 치트시트
golang 치트시트
go 문법 참고자료
go 슬라이스와 맵
고루틴과 채널
go 에러 처리
go cli 명령어
도움이 필요하신가요?
이 도구에서 문제를 발견하셨나요? 저희 팀에 알려주세요.