Basic Types
- boolBoolean
- stringUTF-8 string
- int, int8...int64Signed integers
- uint, uint8...64Unsigned ints
- float32, float64Floats
- bytealias for uint8
- runealias for int32
Variables
// Declaration
var name string = "Go"
var age int // zero value: 0
// Short declaration
name := "Go"
x, y := 1, 2
// Constants
const Pi = 3.14
const (
A = iota // 0
B // 1
)
Go Commands
- go runCompile & run
- go buildCompile binary
- go testRun tests
- go mod initInit module
- go mod tidyClean deps
- go getAdd dependency
- go fmtFormat code
Control Flow
// If statement
if x > 0 {
} else if x < 0 {
} else {
}
// For loop (only loop)
for i := 0; i < 10; i++ {}
for i < 10 {} // while
for {} // infinite
// Range
for i, v := range slice {}
Functions
// Basic function
func add(a, b int) int {
return a + b
}
// Multiple return values
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
// Variadic function
func sum(nums ...int) int {
total := 0
for _, n := range nums { total += n }
return total
}
Structs & Methods
// Struct definition
type Person struct {
Name string
Age int
}
// Method with value receiver
func (p Person) Greet() string {
return "Hello, " + p.Name
}
// Method with pointer receiver
func (p *Person) Birthday() {
p.Age++
}
// Create instance
person := Person{Name: "Alice", Age: 30}
person := &Person{"Alice", 30
Slices & Maps
// Slice
s := []int{1, 2, 3append(s, 4)
s = make([]int, 5)
len(s) // length
cap(s) // capacity
// Map
m := map[string]int{
"a": 1,
}
m["b"] = 2
delete(m, "a")
v, ok := m["key"]
Interfaces
type Writer interface {
Write([]byte) (int, error)
}
// Implicit implementation
type File struct {}
func (f File) Write(b []byte) (int, error) {
return len(b), nil
}
// Type assertion
v, ok := i.(Writer)
Goroutines & Channels
// Start goroutine
go doWork()
// Create channel
ch := make(chan int) // unbuffered
ch := make(chan int, 10) // buffered
// Send and receive
ch <- 42 // send
v := <-ch // receive
// Select
select {
case v := <-ch1:
fmt.Println(v)
case ch2 <- x:
fmt.Println("sent")
default:
fmt.Println("no activity")
}
Error Handling
// Check error
result, err := doSomething()
if err != nil {
return err
}
// Create error
err := errors.New("msg")
err := fmt.Errorf("got %v", v)
// Wrap error (Go 1.13+)
return fmt.Errorf("wrap: %w", err)
Sync Primitives
- sync.MutexMutual exclusion
- sync.RWMutexRead/write lock
- sync.WaitGroupWait for goroutines
- sync.OnceRun once
- sync.MapConcurrent map
Scan a script before you share it — free
Finds credentials, personal data and production hostnames. Runs in your tab.