Getting Started
5 snippetsYour first steps with Go basics
Hello World
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}Comments
// Single line comment
/* Multi-line
comment */User Input
var name string
fmt.Scanln(&name)Type Conversion
strconv.Atoi("42") // string to int
strconv.Itoa(42) // int to string
float64(intValue)Run & Build
go run main.go // Run
go build // Compile
go mod init app // Init moduleVariables & Data Types
7 snippetsStore and manage data in Go
Var
var name string = "John"Short Declaration
age := 25Const
const PI = 3.14159Array
var nums [5]int = [5]int{1, 2, 3, 4, 5}Slice
fruits := []string{"apple", "banana"}Map
ages := map[string]int{"John": 30}Struct
type Person struct {
Name string
Age int
}Operators
7 snippetsSymbols for calculations and comparisons
Arithmetic
+ - * / // Add, Sub, Mul, Div
% // Modulus (remainder)
++ -- // Increment/Decrement (statement only)Comparison
== != // Equal, Not equal
> < // Greater, Less than
>= <= // Greater/Less or equalLogical
&& // AND
|| // OR
! // NOTAssignment
= := // Assign, Short declare
+= -= *= /= %=
&= |= ^= <<= >>=Bitwise
& // AND
| // OR
^ // XOR
&^ // AND NOT (bit clear)
<< // Left shift
>> // Right shiftAddress/Pointer
&x // Address of x
*p // Value at pointer p
*int // Pointer to int typeChannel
<- // Send/receive
ch <- v // Send v to channel
v := <-ch // Receive from channelTired of looking up syntax?
DocuWriter.ai generates documentation and explains code using AI.
Loops
10 snippetsRepeat code efficiently with iterations
For (Classic)
for i := 0; i < 5; i++ {
fmt.Println(i)
}For (While-style)
for count < 10 {
count++
}For (Infinite)
for {
if done { break }
}Range (Slice)
for i, v := range slice {
fmt.Println(i, v)
}Range (Map)
for key, value := range myMap {
fmt.Println(key, value)
}Range (String)
for i, char := range "hello" {
fmt.Printf("%d: %c\n", i, char)
}Ignore Index
for _, v := range slice {
fmt.Println(v)
}Break
for i := 0; i < 10; i++ {
if i == 5 { break }
}Continue
for i := 0; i < 10; i++ {
if i == 5 { continue }
fmt.Println(i)
}Labeled Break
outer:
for i := 0; i < 3; i++ {
for j := 0; j < 3; j++ {
if j == 1 { break outer }
}
}Conditionals
5 snippetsDirect program execution with conditions
If/Else
if x > 0 {
fmt.Println("positive")
} else if x < 0 {
fmt.Println("negative")
} else {
fmt.Println("zero")
}If with Init
if err := doSomething(); err != nil {
fmt.Println(err)
}Switch
switch day {
case "Mon":
fmt.Println("Monday")
case "Tue", "Wed":
fmt.Println("Midweek")
default:
fmt.Println("Other")
}Switch (No Condition)
switch {
case x > 0:
fmt.Println("positive")
case x < 0:
fmt.Println("negative")
}Type Switch
switch v := i.(type) {
case int:
fmt.Println("int", v)
case string:
fmt.Println("string", v)
}Functions
4 snippetsReusable blocks of code
Function
func greet(name string) string {
return "Hello, " + name + "!"
}Multiple Returns
func divide(a, b int) (int, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}Named Returns
func split(sum int) (x, y int) {
x = sum * 4 / 9
y = sum - x
return
}Variadic
func sum(nums ...int) int {
total := 0
for _, n := range nums {
total += n
}
return total
}Error Handling
5 snippetsHandle errors explicitly
Error Check
result, err := doSomething()
if err != nil {
log.Fatal(err)
}Custom Error
errors.New("something went wrong")Wrap Error
fmt.Errorf("failed: %w", err)Defer
defer file.Close()Panic/Recover
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered:", r)
}
}()Concurrency
5 snippetsGoroutines and channels for parallelism
Goroutine
go doSomething()Channel
ch := make(chan int)
ch <- 42
value := <-chBuffered Channel
ch := make(chan int, 100)Select
select {
case msg := <-ch1:
fmt.Println(msg)
case <-time.After(time.Second):
fmt.Println("timeout")
}WaitGroup
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
doWork()
}()
wg.Wait()Interfaces
4 snippetsDefine contracts and behaviors
Interface
type Reader interface {
Read(p []byte) (n int, err error)
}Implement
func (f *File) Read(p []byte) (n int, err error) {
// implementation
}Empty Interface
func print(v interface{}) {
fmt.Println(v)
}Type Assertion
str, ok := v.(string)Generics (Go 1.18+)
5 snippetsType parameters for flexible code
Generic Function
func Min[T ~int | ~float64](a, b T) T {
if a < b {
return a
}
return b
}Type Constraints
type Number interface {
~int | ~int64 | ~float64
}
func Sum[T Number](nums []T) T {
var total T
for _, n := range nums {
total += n
}
return total
}Generic Struct
type Stack[T any] struct {
items []T
}
func (s *Stack[T]) Push(item T) {
s.items = append(s.items, item)
}
func (s *Stack[T]) Pop() T {
item := s.items[len(s.items)-1]
s.items = s.items[:len(s.items)-1]
return item
}Comparable
func Contains[T comparable](slice []T, item T) bool {
for _, v := range slice {
if v == item {
return true
}
}
return false
}Multiple Type Params
func Map[T, U any](items []T, fn func(T) U) []U {
result := make([]U, len(items))
for i, v := range items {
result[i] = fn(v)
}
return result
}Context
5 snippetsRequest-scoped values and cancellation
Background Context
ctx := context.Background()With Timeout
ctx, cancel := context.WithTimeout(
context.Background(),
5*time.Second,
)
defer cancel()With Cancel
ctx, cancel := context.WithCancel(context.Background())
go func() {
<-ctx.Done()
fmt.Println("cancelled")
}()
cancel() // Trigger cancellationWith Value
type key string
ctx := context.WithValue(ctx, key("user"), "john")
// Retrieve
user := ctx.Value(key("user")).(string)Check Done
select {
case <-ctx.Done():
return ctx.Err() // Canceled or DeadlineExceeded
default:
// Continue processing
}Testing
5 snippetsWrite and run tests
Basic Test
// math_test.go
func TestAdd(t *testing.T) {
result := Add(2, 3)
if result != 5 {
t.Errorf("Add(2,3) = %d; want 5", result)
}
}Table Driven
func TestAdd(t *testing.T) {
tests := []struct {
a, b, want int
}{
{1, 2, 3},
{0, 0, 0},
{-1, 1, 0},
}
for _, tc := range tests {
got := Add(tc.a, tc.b)
if got != tc.want {
t.Errorf("Add(%d,%d) = %d; want %d",
tc.a, tc.b, got, tc.want)
}
}
}Subtests
func TestMath(t *testing.T) {
t.Run("Add", func(t *testing.T) {
if Add(1, 2) != 3 {
t.Fail()
}
})
t.Run("Multiply", func(t *testing.T) {
if Multiply(2, 3) != 6 {
t.Fail()
}
})
}Benchmark
func BenchmarkAdd(b *testing.B) {
for i := 0; i < b.N; i++ {
Add(1, 2)
}
}Run Tests
go test // Run all tests
go test -v // Verbose
go test -run Add // Run matching
go test -bench . // Run benchmarksHTTP
6 snippetsBuild web servers and clients
Simple Server
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, World!")
})
http.ListenAndServe(":8080", nil)Handler Interface
type Handler struct{}
func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello"))
}
http.Handle("/", Handler{})GET Request
resp, err := http.Get("https://api.example.com/data")
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)POST with JSON
data := map[string]string{"name": "John"}
jsonData, _ := json.Marshal(data)
resp, err := http.Post(
"https://api.example.com/users",
"application/json",
bytes.NewBuffer(jsonData),
)Custom Client
client := &http.Client{
Timeout: 10 * time.Second,
}
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("Authorization", "Bearer token")
resp, err := client.Do(req)JSON Response
func handler(w http.ResponseWriter, r *http.Request) {
data := map[string]string{"status": "ok"}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(data)
}