Golang Basics Cheatsheet

Tags : go golang google

Types
string
bool
int, uint, uintptr, int8, uint8 (byte), int16, uint16
int32 (rune), uint32, int64, uint64, 
float32, float64
complex64, complex128

byte is an alias of uint8
rune is an alias of int32
Zero values
Zero values
0 for numeric types,
false for the boolean type
"" for strings
Constants declaration
const World = "世界"
const Truth = true
Struct declaration
type Vertex struct {
    X, Y int
}

v := Vertex{1, 2}
Strings operations
// Get a slice of a string
str := "Hello world"
s := str[2:6] // "llo"
Array declaration
var a [2]string
a := [2]string{"Hello", "World"}
Slices declaration
var s []int
s := []int{1, 2, 3}
a := make([]int, 0, 5) // len=0, cap=5

Slice of slice
[][]string{
    []string{1, 2},
    []string{3, 4},
}
Slices operations
// Get a slice of an array
primes := [6]int{2, 3, 5, 7, 11, 13}
var s []int = primes[1:4] // [3, 5, 7]

// Length and capacity
l := len(s)
c := cap(s)

// Append
s := []string{"Hello"}
s = append(s, "World")
Maps declaration
var m map[int]string
m := make(map[int]string)

// Literal declaration
type Vertex struct {
    Lat, Long float64
}
var m = map[string]Vertex{
    "Bell Labs": Vertex{40.68433, -74.39967},
    "Google": Vertex{37.42202, -122.08408},
}
Maps operations
m["Google"] = Vertex{37.42202, -122.08408}

// Does key exist ?
_, ok = m["Google"]

// Delete
delete(m, "Google")
Loops
// Range loop
primes := []int{2, 3, 5, 7, 11, 13}
for i, v := range primes {
    fmt.Printf("loop index %d, value %d\n", i, v)
}