Go Handy Snippets

1func arrayPop(list []int, index int) []int {
2	return append(list[:index], list[index+1:]...)
3}
4evenNumbers := []int{2,4,6,8,9,10}
5evenNumbers = arrayPop(evenNumbers,4)
go
1list1 := []int{1,2,3}
2list2 := []int{4,5,6}
3list3 := []int{7,8,9}
4
5megaList := append(append(list1, list2...), list3...)
6// [1 2 3 4 5 6 7 8 9]
go
1// Traditional swap
2temp := list[0]
3list[0] = list[1]
4list[1] = temp
5
6// Single line swap
7list[0], list[1] = list[1], list[0]
go

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

1// go will panic
2// error: assignment to entry in nil map
3var data map[string]any
4data["foo"] = "bar"
go
1data := make(map[string]any)
2data["foo"] = "bar"
go
 1m := map[string]int {
 2  "one": 1,
 3  "two": 2,
 4}
 5
 6value, ok := m["three"]
 7if ok {} // ok is a bool and will return true is key exists
 8
 9// single line alternative.
10if value, ok := m["two"]; ok {}
...
go