Skip to content

Instantly share code, notes, and snippets.

@ciaranarcher
Last active December 27, 2018 14:26
Show Gist options
  • Save ciaranarcher/9067231 to your computer and use it in GitHub Desktop.
Save ciaranarcher/9067231 to your computer and use it in GitHub Desktop.
golang cheatsheet

Types

type Vertex struct {
    Lat, Long float64
}

Maps

m = make(map[string]Vertex) // Cannot assign to a nil map
m["Bell Labs"] = Vertex{
    40.68433, -74.39967,
}

// map literal
m := map[string]Vertex{
    "Bell Labs": {40.68433, -74.39967}, // Omit the type
    "Google":    {37.42202, -122.08408},
}


m[key] = elem       // Assign
delete(m, key)      // Delete
elem, ok = m[key]   // Reading: ok is false and elem is a zero'd type if not found

Arrays and Slices

a := [2]string
p := []int{2, 3, 5, 7, 11, 13} // size determined from items

p[1:4] // == [3 5 7]
p[:3]  // == [2 3 5]
p[4:]  // == [11 13]

len := 10
a := make([][]uint8, len) // allocates 2-D array and returns slice

Ranges

for i, v := range myArr {
    fmt.Printf("2**%d = %d\n", i, v)
}

for _, value := range myArr { // Ignore the index
    fmt.Printf("%d\n", value)
}

for i := range myArr { // Ignore the value
    myArr[i] = 1 << uint(i)
}

Functions

Functions returning functions

func fibonacci() func() int {
    x := 0
	y := 1
	return func() int {
		x,y = y,x+y
		return x
	}
}

Defined on existing types

func (v *Vertex) Scale(f float64) {
    v.X = v.X * f
    v.Y = v.Y * f
}

func (v *Vertex) Abs() float64 {
    return math.Sqrt(v.X*v.X + v.Y*v.Y)
}

Interfaces

  • An interface type is defined by a set of methods.
  • A value of interface type can hold any value that implements those methods.
type Abser interface {
    Abs() float64
}

var a Abser

a = myType // myType being assigned here must implement the Abs() function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment