Go Handy Snippets

Useful Go-isms

Popping an element from a slice via cutting

  </div>
func arrayPop(list []int, index int) []int {
	return append(list[:index], list[index+1:]...)
}
evenNumbers := []int{2,4,6,8,9,10}
evenNumbers = arrayPop(evenNumbers,4)

Combining 3 slices

  </div>
list1 := []int{1,2,3}
list2 := []int{4,5,6}
list3 := []int{7,8,9}

megaList := append(append(list1, list2...), list3...)
// [1 2 3 4 5 6 7 8 9]

Single line array swaps

  </div>
// Traditional swap
temp := list[0]
list[0] = list[1]
list[1] = temp

// Single line swap
list[0], list[1] = list[1], list[0]

Maps must be initialized

Map types are reference types, like pointers or slices, and so the value of m above is nil; it doesn’t point to an initialized map. A nil map behaves like an empty map when reading, but attempts to write to a nil map will cause a runtime panic; don’t do that. To initialize a map, use the built in make function

docs

  </div>
// go will panic
// error: assignment to entry in nil map
var data map[string]any
data["foo"] = "bar"
  </div>
data := make(map[string]any)
data["foo"] = "bar"

Checking if map key exists

  </div>
m := map[string]int {
  "one": 1,
  "two": 2,
}

value, ok := m["three"]
if ok {} // ok is a bool and will return true is key exists

// single line alternative.
if value, ok := m["two"]; ok {}

Incrementing int values in map

When adding values to a map, go has built in safe guards to ensure the key exists. e.g.

  </div>
pages := make(map[string]int)

// This is the same as... 
if _, exists := pages[urlRef]; exists {
    pages[urlRef]++
} else {
    pages[urlRef] = 1
}

// is the same as 
pages[urlRef]++