home
Golang cheat sheet
Golang in a nutshell
print

Go version: 1.11 - Date: August 2018

Installing Go

Debian/Ubuntu apt update && apt install golang

darwin & brew brew install golang

Other OS/Arch https://golang.org/doc/install

Running your first go program

Executable go programs must be package main

package main 

import "fmt"

// This is a comment
func main() {
    fmt.Println("Hello World ! 你好,世界 ! 😊")
}

Running your program

# Compiling binaries only
> go build -o hello main.go && ./hello
# Compiling and runing (doesn't save a binary)
> go run main.go

# Output
Hello World ! 你好,世界 ! 😊

Cross compilation

# GOOS=operating_system GOARCH=architecture

> GOOS=windows GOARCH=i386 go build -o hello.exe main.go
> GOOS=linux GOARCH=amd64 go build -o hello main.go

# If not specified, go will detect/use the current system and compile for it

Constant and variables

Constant

const myconstant int32 = 1 
myconstant = 5 // program will panic and exit

const LOGLEVEL = 0 // type auto detection 
// LOGLEVEL is of type int32 under 32bit systems, int64 under 64bit systems

Variable

var a int // default value for int is 0
a = 2 + 5
fmt.Println(a) // Will print 7
var a = "hello" // Will panic and exit. Changing type isn't possible.

multiple variables

const (
    PATH = "/etc"
    CONFIG = PATH + "/myconfig.yml"
)
var (
    a = 1
    b = a + 9 // b = 10
    anotherCONFIG = PATH + "/myconfig.ini"
)

Go builtin types

Integers and floats

// Integers
const a uint = 1 // uint8 uint16 uint32 uint64
const b int = 2 // int8 int16 int32 int64
// floats
const c float = 31 // float32 float64
// int, uint, float are respectivly aliases to uint64, int64, float64 in 64 bit systems

Bytes

const a byte = 'a'
const b byte = 97
fmt.Println(a==b) // will print "true"
// In go byte is an alias to uint8 (values from 0 to 255)
const c byte = 256 // error

Strings

s1 := "SII"
var s2 = s1 + " ROCKS !"
fmt.Println(s2) // Will print "SII ROCKS !"

Arrays

// Syntax: []type
var a []int // nil array
var b []int = []int{10, 20, 30}
fmt.Println(a[0]) // Will panic and exit
fmt.Println(b[1]) // Will print: 20

// Allocation
a := make([]int, 4, 10) // lenght: 4, capacity: 10
fmt.Println(a) // Print: [0, 0, 0, 0]

Maps

// Syntax: map[keys_type]values_type
var m map[string]int // nil map
var m := map[string]int{"score": 5000}
fmt.Println(m["score"]) // Print 5000
// Allocation
m = make(map[string]int, 10) // Capacity: 10
m["score"] = 5000
m["year"] = 2018
m["hello"] = "world" // Will panic and exit

Conditions

if 30 > 10{
    fmt.Println("true")
} else if true == false{ 
    fmt.Println("false")
}

Loops

for i:=0;i<10;i++ { // loop in range [0:10[
    fmt.Println("Hello")
}
// loop over array elements/indexes
array := []int{0, 2, 4, 6, 8}
for index, element := range array {
    fmt.Println(index, element)
}
// loop over map keys/values
m := []map[int]bool{0: true, 10, false}
for key, value := range m {
    fmt.Println(key, value)
}

Functions

func SpamHello(ntimes int) (ok bool) {
    for i:=0; i<n;i++ {
        fmt.Println("Hello")
    }
    return true
}

func WriteData(data []byte, filepath string) error {
    if len(data) < 5 {
        return fmt.Errorf("data is too short %v", data)
    }
    
    err := WriteFile(data, path)
    if err != nil {
        return fmt.Errorf("error: %v", err)
    }

    return nil
}

Structs and Pointers

type Book struct {
    Name string
    Author string
    Rating float64
}

var HarryPotterP1 Book = Book{
    Name: "Harry Potter",
    Author: "J.K Rawlings",
}
// Pointers
var mypointer *Book = &Book{Name: "LAMBDA"}
var mypointer2 *Book = &HarryPotterP1

Methods

func (b Book) Description() string {
    return b.Name + " " + b.Author
}

func (b *Book) IncrRating(r float64) float64 {
    b.Rating += r
    return b.Rating
}

func main() {
    b := &Book{}
    b.IncrRating(0.99)
    fmt.Println(b.Rating)
}