Golang Cheatsheet

As I’m learning a new language, it’s a very useful exercise for me to summarize the essence of the language for future personal reference. Golang is an excellent language to learn, and instead of having to Google and juggling between Go’s Playground, StackOverflow, Golang’s Documentation, it’s a lot nicer to have my own reference.

Print to console

fmt.Println("Hello", "World", someVariable)
fmt.Sprintf("my struct: %+v", aStruct)

Formats

%v  the value in a default format
  when printing structs, the plus flag (%+v) adds field names
%#v a Go-syntax representation of the value
%T  a Go-syntax representation of the type of the value
%%  a literal percent sign; consumes no value
%t  the word true or false

Float with values

%f     default width, default precision
%9f    width 9, default precision
%.2f   default width, precision 2
%9.2f  width 9, precision 2
%9.f   width 9, precision 0

Declaring variables:

// constants
const Pi = 3.14
// variables
a := 3
type Job struct {
  i int
  max int
  text string
}
job := new(Job)
job.text = "Hello World"
job.max = 10

Short Variable declarations

var i, j int = 1, 2
k := 3
c, python, java := true, false, "no!"
var (
  ToBe   bool       = false
  MaxInt uint64     = 1<<64 - 1
  z      complex128 = cmplx.Sqrt(-5 + 12i)
)

String

name := "Alex"
name := fmt.Sprintf("my name is %s", name)
paragraph := `
    This is a paragraph
    With new line`

String to bytes Array: []byte("my string")
Number to string: using fmt.Sprintf("%v", intNumber)

import s "strings"
s.Contains("test", "es")         // true
s.Count("test", "t")             // 2
s.HasPrefix("test", "te")        // true
s.HasSuffix("test", "st")        // true
s.Index("test", "e")             // 1
s.Join([]string{"a", "b"}, "-")  // a-b
s.Repeat("a", 5)                 // aaaaa
s.Replace("foo", "o", "0", -1)   // f00
s.Replace("foo", "o", "0", 1)    // f0o
s.Split("a-b-c-d-e", "-")        // [a b c d e]
s.ToLower("TEST")                // test
s.ToUpper("test")                // TEST
len("hello")                     // 5
"hello"[1]                       // 101

Numbers

Parse string to number:

import "strconv"
i, err := strconv.Atoi("-42")

Other:

b, err := strconv.ParseBool("true")
f, err := strconv.ParseFloat("3.1415", 64)
i, err := strconv.ParseInt("-42", 10, 64)
u, err := strconv.ParseUint("42", 10, 64)

Array

tickers := [3]string{"VMW", "CHWY", "OCTF"}
// dynamically guessed array's length
tickers := [...]string{"VMW", "CHWY", "OCTF", "MSFT"}

Slice

Slices use array underneath and automatically allocate new array when the capacity is full

tickers := []string{"VMW", "CHWY", "OCTF"}

2-Dimensional Array/Slice

...

Map

Loop

for index, value := range(array_or_hash) {
  //
}

JSON

Use JSON-to-Go conversion to translate a JSON object to a Golang struct https://mholt.github.io/json-to-go/

For example:

{ "id": 1, "ticker": "TSLA" }
// output
type AutoGenerated struct {
    ID     int    `json:"id"`
    Ticker string `json:"ticker"`
}

Marshal an object to a JSON string:

import "encoding/json"
hash := map[string]interface{}{
  "device":    "iOS"
  "accountType": 1,
  "regionId":    1,
}
payload, err := json.Marshal(hash)

Decode a string to a struct:

var result LoginResponse
json.NewDecoder(resp.Body).Decode(&result)

File

Read the whole file file:

import "io/ioutil"
data, err := ioutil.ReadFile("path/to/file")

Function

func (receiverPointer *type) ExportedMethodName( varName TYPE ) (return type){}

Hello World

package main // must be in main module to execute
import (
  "fmt"
)
func main() {
  fmt.Println("Hello", "World")
}