GO Language Cheat Sheet

This cheat sheet provided basic syntax and methods to help you using Go.

Hello World

package main

import "fmt"

func main() {
    fmt.Println("Hello, world!")
}

Run Directly

$ go run hello.go
Hello, world!

Comments

// Single line comment

/* Multi-
 line comment */

Variables

var s1 string
s1 = "Learn Go!"

// declare multiple variables at once
var b, c int = 1, 2
var d = true

Function

package main

import "fmt"

// The entry point of the programs
func main() {
    fmt.Println("Hello world!")
    say("Hello Go!")
}

func say(message string) {
    fmt.Println("You said: ", message)
}

If Statements

if true {
    fmt.Println("Yes!")
}

String Data Types

s1 := "Hello" + "World"

s2 := "A "raw" string literal
can include line breaks."

// Outputs: 10
fmt.Println(len(s1))

// Outputs: Hello
fmt.Println(string(s1[0:5]))

Number Data Type

num := 3         // int
num := 3.        // float64
num := 3 + 4i    // complex128
num := byte('a') // byte (alias: uint8)

var u uint = 7        // uint (unsigned)
var p float32 = 22.7  // 32-bit float

Operators

x := 5
x++
fmt.Println("x + 4 =", x + 4)
fmt.Println("x * 4 =", x * 4) 

Boolean

isTrue   := true
isFalse  := false

Array

┌────┬────┬────┬────┬─────┬─────┐
| 2  | 3  | 5  | 7  | 11  | 13  |
└────┴────┴────┴────┴─────┴─────┘
  0    1    2    3     4     5

primes := [...]int{2, 3, 5, 7, 11, 13}
fmt.Println(len(primes)) // => 6

// Outputs: [2 3 5 7 11 13]
fmt.Println(primes)

// Same as [:3], Outputs: [2 3 5]
fmt.Println(primes[0:3])
  

Pointers

func main () {
  b := *getPointer()
  fmt.Println("Value is", b)
}

Slices

s := make([]string, 3)
s[0] = "a"
s[1] = "b"
s = append(s, "d")
s = append(s, "e", "f")

fmt.Println(s)
fmt.Println(s[1])
fmt.Println(len(s))
fmt.Println(s[1:3])

slice := []int{2, 3, 4}

Constant

const s string = "constant"
const Phi = 1.618
const n = 500000000
const d = 3e20 / n
fmt.Println(d)

Type Conversion

i := 90
f := float64(i)
u := uint(i)

// Will be equal to the character Z
s := string(i)

String Function

package main

import (
	"fmt"
	s "strings"
)

func main() {
    /* Need to import strings as s */
	fmt.Println(s.Contains("test", "e"))

    /* Build in */
    fmt.Println(len("hello"))  // => 5
    // Outputs: 101
	fmt.Println("hello"[1])
    // Outputs: e
	fmt.Println(string("hello"[1]))

}

fmt.Printf

package main

import (
	"fmt"
	"os"
)

type point struct {
	x, y int
}

func main() {
	p := point{1, 2}
	fmt.Printf("%v
", p)                        // => {1 2}
	fmt.Printf("%+v
", p)                       // => {x:1 y:2}
	fmt.Printf("%#v
", p)                       // => main.point{x:1, y:2}
	fmt.Printf("%T
", p)                        // => main.point
	fmt.Printf("%t
", true)                     // => TRUE
	fmt.Printf("%d
", 123)                      // => 123
	fmt.Printf("%b
", 14)                       // => 1110
	fmt.Printf("%c
", 33)                       // => !
	fmt.Printf("%x
", 456)                      // => 1c8
	fmt.Printf("%f
", 78.9)                     // => 78.9
	fmt.Printf("%e
", 123400000.0)              // => 1.23E+08
	fmt.Printf("%E
", 123400000.0)              // => 1.23E+08
	fmt.Printf("%s
", ""string"")             // => "string"
	fmt.Printf("%q
", ""string"")             // => ""string""
	fmt.Printf("%x
", "hex this")               // => 6.86578E+15
	fmt.Printf("%p
", &p)                       // => 0xc00002c040
	fmt.Printf("|%6d|%6d|
", 12, 345)           // => |    12|   345|
	fmt.Printf("|%6.2f|%6.2f|
", 1.2, 3.45)     // => |  1.20|  3.45|
	fmt.Printf("|%-6.2f|%-6.2f|
", 1.2, 3.45)   // => |1.20  |3.45  |
	fmt.Printf("|%6s|%6s|
", "foo", "b")        // => |   foo|     b|
	fmt.Printf("|%-6s|%-6s|
", "foo", "b")      // => |foo   |b     |

	s := fmt.Sprintf("a %s", "string")
	fmt.Println(s)

	fmt.Fprintf(os.Stderr, "an %s
", "error")
}

Conditional Flow control


a := 10

if a > 20 {
    fmt.Println(">")
} else if a < 20 {
    fmt.Println("<")
} else {
    fmt.Println("=")
}

Switch Statement

x := 42.0
switch x {
case 0:
case 1, 2:
    fmt.Println("Multiple matches")
case 42:   // Don't "fall through".
    fmt.Println("reached")
case 43:
    fmt.Println("Unreached")
default:
    fmt.Println("Optional")
}

For Loop

for i := 0; i <= 10; i++ {
  fmt.Println("i: ", i)
}

For-Range Loop

nums := []int{2, 3, 4}
sum := 0
for _, num := range nums {
    sum += num
}
fmt.Println("sum:", sum)

While Loop

i := 1
for i <= 3 {
    fmt.Println(i)
    i++
}

Continue Keyword

for i := 0; i <= 5; i++ {
    if i % 2 == 0 {
        continue
    }
    fmt.Println(i)
}

Break Keyword

for {
    fmt.Println("loop")
    break
}

Struct & map Define

package main

import (
	"fmt"
)

type Vertex struct {
	X int
	Y int
}

func main() {
	v := Vertex{1, 2}
	v.X = 4
	fmt.Println(v.X, v.Y) // => 4 2
}

Literals

v := Vertex{X: 1, Y: 2}
// Field names can be omitted
v := Vertex{1, 2}
// Y is implicit
v := Vertex{X: 1}

Maps

m := make(map[string]int)
m["k1"] = 7
m["k2"] = 13
fmt.Println(m) // => map[k1:7 k2:13]

v1 := m["k1"]
fmt.Println(v1)     // => 7
fmt.Println(len(m)) // => 2

delete(m, "k2")
fmt.Println(m) // => map[k1:7]

_, prs := m["k2"]
fmt.Println(prs) // => false

n := map[string]int{"foo": 1, "bar": 2}
fmt.Println(n) // => map[bar:2 foo:1]

Multiple argument function

func plus(a int, b int) int {
    return a + b
}
func plusPlus(a, b, c int) int {
    return a + b + c
}
fmt.Println(plus(1, 2))
fmt.Println(plusPlus(1, 2, 3))

Multiple Return

func vals() (int, int) {
    return 3, 7
}

a, b := vals()
fmt.Println(a)    // => 3
fmt.Println(b)    // => 7

Naked return

func split(sum int) (x, y int) {
  x = sum * 4 / 9
  y = sum - x
  return
}

x, y := split(17)
fmt.Println(x)   // => 7
fmt.Println(y)   // => 10

Variadic functions

func sum(nums ...int) {
    fmt.Print(nums, " ")
    total := 0
    for _, num := range nums {
        total += num
    }
    fmt.Println(total)
}
sum(1, 2)     //=> [1 2] 3
sum(1, 2, 3)  // => [1 2 3] 6

nums := []int{1, 2, 3, 4}
sum(nums...)  // => [1 2 3 4] 10

Function as values

func main() {
    // assign a function to a name
    add := func(a, b int) int {
        return a + b
    }
    // use the name to call the function
    fmt.Println(add(3, 4)) // => 7
}

Closure

func scope() func() int{
    outer_var := 2
    foo := func() int {return outer_var}
    return foo
}

// Outpus: 2
fmt.Println(scope()())

Import Packages

import "fmt"
import "math/rand"

Export Name

// Begin with a capital letter
func Hello () {
  ···
}

Go Concurrency Goroutines

package main

import (
	"fmt"
	"time"
)

func f(from string) {
	for i := 0; i < 3; i++ {
		fmt.Println(from, ":", i)
	}
}

func main() {
	f("direct")
	go f("goroutine")

	go func(msg string) {
		fmt.Println(msg)
	}("going")

	time.Sleep(time.Second)
	fmt.Println("done")
}

Wait Group

package main

import (
	"fmt"
	"sync"
	"time"
)

func w(id int, wg *sync.WaitGroup) {
	defer wg.Done()
	fmt.Printf("%d starting
", id)

	time.Sleep(time.Second)
	fmt.Printf("%d done
", id)
}

func main() {
	var wg sync.WaitGroup
	for i := 1; i <= 5; i++ {
		wg.Add(1)
		go w(i, &wg)
	}
	wg.Wait()
}

Closing channel

ch <- 1
ch <- 2
ch <- 3
close(ch) // Closes a channel

Error control

func main() {
  defer func() {
    fmt.Println("Done")
  }()
  fmt.Println("Working...")
}

Lambda Defer

func main() {
  var d = int64(0)
  defer func(d *int64) {
    fmt.Printf("& %v Unix Sec
", *d)
  }(&d)
  fmt.Print("Done ")
  d = time.Now().Unix()
}

Go Method Receivers

type Vertex struct {
  X, Y float64
}

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

A Basic Interface

type Shape interface {
  Area() float64
  Perimeter() float64
}

Struct

type Rectangle struct {
  Length, Width float64
}

Methods

func (r Rectangle) Area() float64 {
  return r.Length * r.Width
}

func (r Rectangle) Perimeter() float64 {
  return 2 * (r.Length + r.Width)
}

Interface Example

func main() {
  var r Shape = Rectangle{Length: 3, Width: 4}
  fmt.Printf("Type of r: %T, Area: %v, Perimeter: %v.", r, r.Area(), r.Perimeter())
}