arunsah.github.io

Go Cheatsheet

πŸ“… 2020-05-09 πŸ–ŠοΈ @arunsah 🧭 Pune, India


Getting started

$ go
Go is a tool for managing Go source code.

Usage:

        go <command> [arguments]

The commands are:

        bug         start a bug report
        build       compile packages and dependencies
        clean       remove object files and cached files
        doc         show documentation for package or symbol
        env         print Go environment information
        fix         update packages to use new APIs
        fmt         gofmt (reformat) package sources
        generate    generate Go files by processing source
        get         add dependencies to current module and install them
        install     compile and install packages and dependencies
        list        list packages or modules
        mod         module maintenance
        run         compile and run Go program
        test        test packages
        tool        run specified go tool
        version     print Go version
        vet         report likely mistakes in packages

Use "go help <command>" for more information about a command.

Additional help topics:

        buildmode   build modes
        c           calling between Go and C
        cache       build and test caching
        environment environment variables
        filetype    file types
        go.mod      the go.mod file
        gopath      GOPATH environment variable
        gopath-get  legacy GOPATH go get
        goproxy     module proxy protocol
        importpath  import path syntax
        modules     modules, module versions, and more
        module-get  module-aware go get
        module-auth module authentication using go.sum
        module-private module configuration for non-public modules
        packages    package lists and patterns
        testflag    testing flags
        testfunc    testing functions

Use "go help <topic>" for more information about that topic.


$ go version
go version go1.13.8 darwin/amd64

$ cat hello_world.go 
package helloworld

import "fmt"

func main() {
        fmt.Println("hello world")
}

$ go build hello_world.go 

$ ls
hello_world.go

$ ls -all
total 8
drwxr-xr-x  3 arunsah  staff  96  9 May 21:44 .
drwxr-xr-x  3 arunsah  staff  96  9 May 21:44 ..
-rw-r--r--  1 arunsah  staff  78  9 May 21:45 hello_world.go

$ go run hello_world.go 
go run: cannot run non-main package

$ cat hello_world.go 
package main

import "fmt"

func main() {
        fmt.Println("hello world")
}

$ go build hello_world.go 

$ ls -all
total 4152
drwxr-xr-x  4 arunsah  staff      128  9 May 21:48 .
drwxr-xr-x  3 arunsah  staff       96  9 May 21:44 ..
-rwxr-xr-x  1 arunsah  staff  2120320  9 May 21:48 hello_world
-rw-r--r--  1 arunsah  staff       72  9 May 21:48 hello_world.go

$ ./hello_world 
hello world

$ go run hello_world.go 
hello world

$ go build hello_world.go  && ./hello_world 
hello world

Cheatsheet

Variables

// variable declaration
var msg string
msg = "hello world"

// variable declaration and initiaization
msg:= "hello world"

Constants

const Pi = 3.141

Basic Type

// string
msg:= "hello world"
// multi-line string
msg:= `Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. 
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.`

// numbers
num:= 42					// int
num:= 42.					// float64
num:= 42 + 3i				// complex128
num:= byte('A')			// byte, alias for uint8

var age uint = 26			// uint
var pi float32 = 3.141	// float32

// arrays have fixed size
nums := [...]int{1,2,3,4,5}
nums := [5]int{1,2,3,4,5}

// slices have dynamic size
nums := []int{1,2,3,4,5}
data := []byte("hello world")


Pointers
// pointers point to a memor location of a variable.
// go is garbage-collected language 
func main(){
	b := *getValueByReference()
	...
}

func getValueByReference() (x *int){
	value:= 42
	return &value
}
Type Conversions
iNum := 42
fNum := float64(iNum)
uNum := uint(iNum)

Control Flow and Loop Example

FizzBuzz example
// FizzBuzz program: for i= 1 to 20, 
// if i is multiple of 3 and 5 then print 'Fizz buzz', 
// if i is numtiple of 3 then print 'fizz', 
// if i is numtiple of 5 then print 'buzz' 
// else print the number
package main

import (
    "fmt"
    "strconv"
)

func main() {
    fmt.Println("hello world")

    var msg string
    for num := 0; num <= 20; num++ {
        if num%3 == 0 && num%5 == 0 {
            msg = "fizz buzz"
        } else if num%3 == 0 {
            msg = "fizz"
        } else if num%5 == 0 {
            msg = "buzz"
        } else {
            // conveting number to string
            msg = strconv.Itoa(num)
            //msg = strconv.FormatInt(int64(num), 10)
        }
        fmt.Println(msg)
        //fmt.Printf("%v\n", msg)
    }
}

// statements in if: condition in if can be preceded with a statement before ;
if _, err := getResult(); err != nil{
	// handle error
}


// switch
day := "sunday"
switch day {
case "saturday":
    fallthrough // cases doesnot fall by default
case "sunday":
    msg = "weekend"
default:
    msg = "workday"
}


// for loop
for i:= 0; i<10; i++}
	//...
}

// for range loop
names := []string{"tom", "jerry", "nibbles", "droopy"}
for index, name := range names {
    fmt.Printf("%d, %s\n", index, name)
}

Functions

Lambda
// legal voting age is 18 in India
canVote := func(age int) bool { return age >= 18 }
age := 17
fmt.Printf("Age: %v, can vote: %v\n", age, canVote(age))

Multiple return types
fmt.Println(getName()) // Michael Jackson
a, b := getName()
fmt.Printf("First name: %v, Last name: %v\n", a, b) // First name: Michael, Last name: Jackson

func getName() (firstName, lastName string) {
    return "Michael", "Jackson"
}

// by defining return value identifier in signatiure,
// return statement with no args will return variables with those identifier name
func getSize() (width, height float64) {
    width = 32
    height = 30
    return
}
fmt.Println(getSize())	// 32 30

Packages

// import statement per package
import "fmt"
import "math/rand"

// import statement grouped together
import (
	"fmt"		//fmt.Println
	"math/rand"	//rand.Intn
)

// import with alias
import randomNumber "math/rand" 	// randomNumber.Intn


// every package file starts with package name
package main

// Function with Capital names are exposes in the package

Exposing Methods

//---------- directory structure ----------------
mario:hello_world arunsah$ tree
.
β”œβ”€β”€ hello
β”‚   └── Hello.go		//package hello
β”œβ”€β”€ hello_world
└── hello_world.go	//package main

//---------- ./hello/Hello.go ----------------
package hello

/*
Hello return string "hello"
*/
func Hello() string { // method name must start with upper case
						// to expose the method outside package
						// Documentation is compulsory
    return "hello"
}

//---------- ./hello_world.go ----------------
package main

import (
    hello "./hello"				//exposing via alias
)

func main() {
    fmt.Println(hello.Hello())
}

Concurrency

Go routines
func publish(message string, messageQueue chan string) {
    messageQueue <- "Hello, " + message + "! "
}

// create channel
messageQueue := make(chan string)

// start concurrent go routines
// publish to channel
// order of execution is not guranted
go publish("tom", messageQueue)
go publish("jerry", messageQueue)
go publish("droopy", messageQueue)
go publish("nibbles", messageQueue)

// read from channel/messageQueue
fmt.Println(<-messageQueue,
    <-messageQueue,
    <-messageQueue,
    <-messageQueue)
// Hello, nibbles!  Hello, tom!  Hello, jerry!  Hello, droopy!
// Hello, nibbles!  Hello, jerry!  Hello, droopy!  Hello, tom!


// iterates across a channel until its closed
for msg := range messageQueue { // iterated until closed
    fmt.Println(msg)
}

// read with repetation
for true {
    if greetingMsg, isClosed := <-messageQueue; isClosed != false {
        fmt.Println(greetingMsg)
        // close(messageQueue) // shutdown channel
        if isClosed == true {
            break //break loop
        }
    }
}

References

The Go Programming Language Specification

Version of Jan 14, 2020 https://golang.org/ref/spec

Introduction, Notation, Source code representation, Characters, Letters and digits, Lexical elements, Comments, Tokens, Semicolons, Identifiers, Keywords, Operators and punctuation, Integer literals, Floating-point literals, Imaginary literals, Rune literals, String literals, Constants, Variables, Types, Method sets, Boolean types, Numeric types, String types, Array types, Slice types, Struct types, Pointer types Function types, Interface types, Map types, Channel types, Properties of types and values, Type identity, Assignability, Representability, Blocks, Declarations and scope, Label scopes, Blank identifier, Predeclared identifiers, Exported identifiers, Uniqueness of identifiers, Constant declarations, Iota, Type declarations, Variable declarations, Short variable declarations, Function declarations, Method declarations, Expressions, Operands, Qualified identifiers, Composite literals, Function literals, Primary expressions, Selectors, Method expressions, Method values, Index expressions, Slice expressions, Type assertions, Calls, Passing arguments to … parameters, Operators, Arithmetic operators, Comparison operators, Logical operators, Address operators, Receive operator, Conversions, Constant expressions, Order of evaluation, Statements, Terminating statements, Empty statements, Labeled statements, Expression statements, Send statements, IncDec statements, Assignments, If statements, Switch statements, For statements, Go statements, Select statements, Return statements, Break statements, Continue statements, Goto statements, Fallthrough statements, Defer statements, Built-in functions, Close, Length and capacity, Allocation, Making slices, maps and channels, Appending to and copying slices, Deletion of map elements, Manipulating complex numbers, Handling panics, Bootstrapping, Packages, Source file organization, Package clause, Import declarations, An example package, Program initialization and execution, The zero value, Package initialization, Program execution, Errors, Run-time panics, System considerations, Package unsafe, Size and alignment guarantees

Go Standard library

Packages - The Go Programming Language

Sub-repositories

These packages are part of the Go Project but outside the main Go tree. They are developed under looser compatibility requirements than the Go core. Install them with β€œ go get β€œ.

References