Dev In The Mountain Header
A Developer In The mountains having fun

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)

go
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):

go
s := []int{1, 2, 3}
for k, v := range s {
  fmt.Println(k,v)
}

looping with only a test

go
for test {}

looping forever (until something inside the loop breaks)

go
for {}

exiting from a loop early:

  • break
  • continue
  • labels SOMELABEL: -- defines which level to break to break 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

go
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

  • &x gets a pointer to x and *int is 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.

go
p := new(int) // p is a *int
*p = 5

Functions

  • functions can be passed as values
  • anonymous functions can be used
  • can be immediately invoked

nothing passed in or out:

go
func myFuncName() {}

multiple types passed in

go
func myFuncName(greeting string, id int) {}

multiple types passed in, and multiple returned

go
func myFuncName(greeting string, id int) (string, int){
  return greeting, id
}

multiple of same types passed in

go
func myFuncName(greeting, saying string) {}

passing pointers to function (so it changes the main var)

go
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

go
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.

go
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.

go
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.

More places to find me
Mental Health
follow me on Mastodon