Last reviewed
Go Lang Cheat Sheet
capital variables/stucts are exported(public)
lower-case variables are not exported(private)
camelCasing is convention no underscores or dashes should be used in variables
Maps:
Collection of like value types maps — not ordered
Get value:
- myVal := mapName[val] a missing key returns the zero value for the value type (0, "", nil...)
- myVal, ok := mapName[val] ok is false when the key is missing
map functions
delete(mapName, valueToDel)
Struct
Flexable container for diffrent data types one struct can be embeded within anouther (add without type)
type structName struct {
someName int
someName2 string
someName3 []string
}Get Value:
- structName.someName
- structName.someName3[2]
Loops:
only one kind of loop in Go and that is the For loop
basic for loop styles:
for i := 0; i < 9; i++ {}for ; i < 9; i++ {}for i := 0; i < 9; {}for i < 9 {}for i := range 9 {}(Go 1.22+, i counts from 0 to 8)
looping over a slice,array, map, string, channel (capturing keys & values):
s := []int{1, 2, 3}
for k, v := range s {
fmt.Println(k,v)
}looping with only a test
for test {}looping forever (until something inside the loop breaks)
for {}exiting from a loop early:
breakcontinue- labels
SOMELABEL:-- defines which level to break tobreak SOMELABEL
Flow Control:
Defer
defer runs after the function, but before returning: Last in, first out order if multiple defers.
- useful for keeping statments that close a resource close to the open
- arguments are taken at the time of the defer statement not when run
Panic
- a panic doesn't have to be fatal
- defer statments happen before a panic
- recover will allow panic to be recovered from
ie:
panic("message: " + err.Error())
example of a recovery of a panic inside a defer statement
func main() {
fmt.Println("start")
defer func() { // this is an anonymous function
if err := recover(); err != nil {
log.Println("Error: ", err)
}
}() // this is needed to actually call the function
panic("something bad happened") // this is panic and not print "end",
// but if this was inside anouther function it would recover to the end of the function
fmt.Println("end")
}Pointers
&xgets a pointer to x and*intis the type "pointer to an int"- points to the memory address
- allows a refrence (pointer) instead of a copy of a variable.
- and (*) before a variable "dereferences" it to the value.
slices/maps hold a reference to their underlying data
- changing the data through one copy of a slice or map changes it for the others that share that data.
New keyword
new(T) allocates a zero value of type T and returns a pointer to it.
p := new(int) // p is a *int
*p = 5Functions
- functions can be passed as values
- anonymous functions can be used
- can be immediately invoked
nothing passed in or out:
func myFuncName() {}multiple types passed in
func myFuncName(greeting string, id int) {}multiple types passed in, and multiple returned
func myFuncName(greeting string, id int) (string, int){
return greeting, id
}multiple of same types passed in
func myFuncName(greeting, saying string) {}passing pointers to function (so it changes the main var)
func main() {
name := "Stacey"
myFuncName(&name)
}
func myFuncName(name *string) {
*name = "Sam" // this changees the name in main too
}passing multiple values into function that become a slice
func main() {
myFuncName(1, 5, 60, 40)
}
func myFuncName(values ...int) {
result := 0
for _, v := range values {
result += v
}
}Methods
A method is a function with a receiver. Use a pointer receiver when the method needs to change the value.
type counter struct {
total int
}
func (c counter) current() int { // value receiver, works on a copy
return c.total
}
func (c *counter) add(n int) { // pointer receiver, changes the original
c.total += n
}Generics
Added in Go 1.18. Type parameters let a function or type work with many types.
func Map[T, U any](items []T, f func(T) U) []U {
result := make([]U, 0, len(items))
for _, item := range items {
result = append(result, f(item))
}
return result
}Documentation
Documentation is important and that is one reason that Documentation in Golang is directly inside the code. This also helps keep the Documentation close to the code that it is documenting, helping to keep it up-to-date as its easy to edit at the same time the code is edited.

