This cheatsheet was created by one of my colleague Austin. Just sharing it here because I found it useful
Install Go on your MAC
Follow these steps to install go onto your mac and test out the installation
Brief Intro
- fmt is the main package for printing stuff
- fmt.Println(“something”)
- fmt.Printf(“I have %d items”, 4)
- Initializing variables
- var a string default to “”
- var b int default to 0
- var c bool default to false
- a := “” will infer a is a string
- b := 0 will infer b is an int
- c := false will infer c is a bool
- var d int
- d = 5
- Is the same as d := 5
- Case matters!!
- Uppercase first letter means exporting variable, struct, function outside the package
- Lowercase means variable, struct, function can only be used within package
- for is the only looping expressions
- for {... somewhere a break} is a while loop with some condition to break out
- for i := 0; i < N; i++ {...} is the standard for loop
- for key, val := range myMap {...} iterates over each key in a map or in python a dict
- for index, val := range mySlice {...} enumerates over a slice or in python a list
- Slices are like lists in the python
- s := []int{1,2,3} creates a slice of int with 3 integers
- s := make([]int, 5) initializes a slice of int set to 0 with a len and capacity of 5
- s := make([]int, 0, 5) initializes a slice of int with len of 0 and capacity of 5
- Maps are like dicts in python
- Must make before using
- var b map[string]int results in b == nil and setting a key will result in a panic: assignment to entry in nil map
- b := make(map[string]int) results in b != nilFunnnna
- Functions
- func myFuncName(a, b int) int { return a+b }
- In go everything is pass by value - Rob Pike
- Treat structs, ints, float64, bool all as copied into a function
- Maps and slices are passed in by their pointer so changing the values in the function changes the passed in map/slice
- To retain the changes made to a struct, be sure to pass the struct’s address into the function instead of the struct itself
- Go routines
- Very light weight ~ 4-8kb
- Are scheduled onto threads
- Could have thousands or millions of these running
import (
“time”
“fmt”
)
func main() {
for i := 1; i < 4; i ++ {
go func(sleepTime int) {
time.Sleep(sleepTime *time.Seconds)
fmt.Printf(“Finished sleeping %d seconds”, sleepTime)
}(i)
}
time.Sleep(5 * time.Seconds)
}
-
Sync waitgroup
- Wait for a set number of go routines to complete
- Add(n int) - set the number of go routines the wait group will wait to finish
- Done() - lets a go routine signal it is done
- Wait() - holds here for all go routines to finish
-
Mutex
- Allows you to lock a particular data structure, be it a struct or different levels of the struct
type MyStruct { sync.Mutex Data []int }
- Lock()
- Unlock()
- b := MyStruct{}
- b.Lock()
- Do some stuff to the data field
- b.Unlock()
- Allows another go routine to modify the struct