Skip to content

dennyzhang/cheatsheet-golang-A4

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

1 Golang CheatSheet

linkedin
github
slack


PRs Welcome

File me Issues or star this repo.

1.1 Golang Conversion

NameComment
Convert string to inti, _ := strconv.ParseInt(“12345”, 10, 64)
Convert string to inti, err := strconv.Atoi(“-42”)
Convert string to listL := strings.Split(“hi,golang”, “”)
Convert string to []byte[]byte("abcXX")
Convert string to bytebyte(str1[])
Convert byte to stringstring(byte('a'))=
Convert string to float32f, _ := strconv.ParseFloat(“3.1415”, 32)
Convert int to float320.5*float32(age)+7>= float32(age2)
Convert int to strings := strconv.Itoa(-42). Notice: not string(-42)
Convert rune to stringstring(rune1)
Convert string list to stringstrings.Join(list, ", ")
Convert int list to stringfmt.Sprintf("%s", l)
Convert list to bytebyteI := byte(65)
Convert byte to intint(byte('a'))
Convert byte to stringstring(byte('a'))
Convert bytes to stringstring([]byte("abcXX"))
Convert int32 to int32 Pointerfunc int32Ptr(i int32) *int32 { return &i }
Convert string[] to stringstrings.Join([]string{"a", "b"}, ",")
Format stringfmt.Sprintf("%.3f", float64(v)/1000)
Format stringfmt.Sprintf("At %v, %s", e.When, e.What)
Format stringfmt.Printf("int: %d, float: %f, bool: %t\n", 123, 78.9, true)

1.2 Deep Dive Into Golang

  • Go’s original target was networked system infrastructure, what we now call cloud software
NameComment
Golang goroutine
How Golang implement =defer=Execute a piece of code before a function returns with FILO mechanism
How Golang implement timer
Golang for vs loop
Garbage Colection
Golang CSP vs Erlang Actor ModelEach actor model, which actor has its own queue
How Golang channel feature is implement?YouTube: GopherCon 2017: Understanding Channels, Link: Golang Channel
Golang return a tuplefunc dfs(root *TreeNode, max *float64) (sum int, cnt int), LeetCode: Maximum Average Subtree
Use strings.Builder, instead of stringLeetCode: Unique Email Addresses
Variable Conversionfloat64(x_int/y_int) != float64(x_int)/float64(y_int), LeetCode: Maximum Average Subtree
For a list of objects, pass by value or referencef(l []*TreeNode) vs f(l *[]*TreeNode), LeetCode: Lowest Common Ancestor of a Binary Tree

1.3 Golang Quality Improvement Tools

NameComment
gosecGolang security checker, gosec ./...
golangci-lintlint check, golint
errcheckerrcheck checks that you checked errors, errcheck ./...
delveDelve is a debugger for the Go programming language.
ginkgoBDD Testing Framework for Go
mockGoMock is a mocking framework for Golang
envtestprovides libraries for integration testing by starting a local control plane
go-junit-reportConvert go test output to junit xml
gocover-coberturago tool cover to XML (Cobertura) export tool
gocovmergeMerge coverprofile results from multiple go cover runs

1.4 Golang Dependencies

NameComment
goimportsupdates your Go import lines, adding missing ones and removing unreferenced ones
depGo deps, now recommend go modules
Install go depgo get -u github.com/golang/dep/cmd/dep
Go modulesexport GO111MODULE=on, go mod download
Initialize new module in current directorygo mod init XXX
Download modules to local cachego mod download
Add missing and remove unused modulesgo mod tidy
Make vendored copy of dependenciesgo mod vendor
ReferenceLink: Using Go Modules

1.5 Golang Errors

NameComment
… does not support indexing*variable[0] -> (*variable)[0]

1.6 Golang Common

NameComment
Upgrade golang to 1.12 in macbrew upgrade go, go version
ReferenceLink: The Go Programming Language Specification

1.7 Golang Code Structure & Common Algorithms

NameComment
Online Go Playgroudhttps://play.golang.org/
One line if statementif a >= 1 { fmt.Print(“yes”) }
Declare variables with initializersvar ischecked, v, str = false, 2, “yes!”
goroutineDefine functions to run as distince subprocesses
switchcode/example-switch.go
queueLeetCode: Number of Recent Calls
bfscode/tree-bfs.go
trie treecode/tree-trie.go

1.8 Syntax Sugar: From Python To Golang

NamePythonGolang
sum slicesum([1, 2, 3])sum := 0; for i := range nums { sum += nums[i] }
Get last itemnums[-1]nums[len(nums)-1]
Forfor i in range(10):for i := 0; i < 10; i++
Loop listfor num in [1, 2]for num := range[]int{1, 2} { fmt.Print(num) }
Loop stringfor ch in str:for _, ch := range str { fmt.Print(ch) }
Iteratorfor num in nums:for _, num := range nums {fmt.Print(num)}
Whilewhile isOK:for isOK
Check ch rangeord(ch) in range(ord('a'), ord('z')+1)ch >=’a’ && ch <=’z’
Get minmin(2, 6, 5)
Check is nilroot is Noneroot == nil
Reverse listnums[::-1]Need to create your own function. Weird!

1.9 Surprises In Golang

NameComment
Modulus returns negative numbersIn golang, -3 % 2 == -1

1.10 Golang Array/List/Slice

NameComment
Make a arrayvar a [2]string; a[0]=”hello”; a[1]=”world”
Create array with given valuesl := [6]int{2, 3, 7, 5, 11, 13}
Create array with given valuesl := []string{“a”, “c”, “b”, “d”}
Create dynamically-sized arraysa := make([]int, 5)
Create dynamically-sized arraysa := make([]int, 1, 5) // 5 is capacity
Sort string arraysort.Strings(l); fmt.Print(l)
Sort int arraysort.Ints(l) //in-place change
Golang sort one array by another arrayLeetCode: Largest Values From Labels
Sort in descending ordersort.Sort(sort.Reverse(sort.IntSlice(keys)))
Append iteml = append(l, “e”)
Append itemsl = append(l, “e”, “b”, “c”)
Append item to head/prependl = append([]string{"a"}, l...)
Remove last iteml = l[:len(l)-1]
Remove item by indexl = append(l[0:1], l[2:]...)
Slices of a arrayvar l2 = l[1:3] // Notice: it’s a reference
Copy a listb := make([]int, len(a)); copy(b, a)
Join two listsl1 = append(l1, l2...)
Use pointer of array listcode/pointer-array.go

1.11 Golang String

NameComment
Format stringfmt.Sprintf("At %v, %s", e.When, e.What)
Format stringfmt.Printf("int: %d, float: %f, bool: %t\n", 123, 78.9, true)
Padding zerofmt.Printf("%02d:%02d", 2, 10)
Split stringvar L = strings.Split("hi,golang", ",")
Replace stringvar str2 = strings.Replace("hi,all", ",", ";", -1)
Replace stringstrings.Replace("aaaa", "a", "b", 2) //bbaa
Split string by separatorstrings.Split(path, " ")
Count charactersstrings.Count("test", "t")
Substringstrings.Index("test", "e")
Join stringstrings.Join([]string{"a","b"}, "-")
Repeat stringstrings.Repeat("a", 2) // aa
Lower stringstrings.ToLower("TEST")
Trim whitespace in two sidesstrings.TrimSpace("\t Hello world!\n ")
Trim trailing whitespacestrings.TrimRight("\t Hello world!\n ", "\n ")
Concact stringfmt.Sprintf("%s%s", str1, str2)
ReferenceLink: package strings

1.12 Golang Integer/Float

NameComment
Int maxMaxInt32 = 1<<31 - 1 golang math
Int minMinInt32 = -1 << 31 golang math
Pass int as referencesample code

1.13 Golang Env

NameComment
GOPATHIt is called as the workspace directory for Go programs
GOROOTThe location of your Go installation. No need to set any more
go envShow a full list of environment variables
ReferenceLink: GOPATH, GOROOT, GOBIN

1.14 Golang Package management

NameComment
go modLink: go modules
go get fixGO111MODULE=off go get -fix ./...
go mod replace urlgo mod edit -replace…

1.15 Golang Ascii

NameComment
get character asciibyte('0')
ascii offsetfmt.Println(string('B' + byte('a')-byte('A')))

1.16 Golang Dict/Hashmap/Map

NameComment
Create dictmap[string]int{"a": 1, "b": 2}
Create dictmake(map[string]int)
Check existence_, ok := m[k]
Delete keydelete(m, "k1")
Create a map of listsm := make(map[string][]string)
Get keys of a mapLoop the dictionary and append the key to a list
Use (x, y) as hashmap keym[[2]int{2, 2}] = true, code/example-hashmap-arraykey.go

1.17 Golang Networking

NameComment
golang httpcode/example-http.go

1.18 Golang Goroutines

NameComment
Basic goroutinecode/example-goroutine.go

1.19 Golang Inteface

NameComment
Hash map with both key and value dynamicmap[interface{}]interface{}
Define and use interfacecode/example-interface.go
Convert map[interface {}]interface {} to map[string]stringcode/interface-conversion.go

1.20 Golang Files & Folders

NameComment
Read filescode/example-read-file.go
Write filescode/example-write-file.go

1.21 Golang Math

NameComment
pow(2, 3)int(math.Pow(2, 3)) // Default is float64
sqrtmath.Sqrt(100)
Get randrand.Intn(100), rand.Float64()

1.22 Golang Bit Operator & Math

NameComment
Shift leftfmt.Print(1 << 10) // 1024
Shift rightfmt.Print(1024 >> 3) // 128

1.23 Golang BBD Testing

NameSummary
ginkgoBDD Testing Framework for Go http://onsi.github.io/ginkgo/
Ubuntu install ginkgoapt-get install golang-ginkgo-dev
gomegaGinkgo’s Preferred Matcher Library
Add tags to tests// +build availability, go test -v --tags=availability ./test/e2e/...

1.24 Golang Misc

NameComment
Golang sleeptime.Sleep(4* time.Second)
Golang loggingimport "log", log.Info, log.Print, log.Error(err)
Golang print function nameruntime.Callers

1.25 More Resources

https://play.golang.org/

https://tour.golang.org/list

https://golang.org/doc/

https://github.com/a8m/go-lang-cheat-sheet

License: Code is licensed under MIT License.

linkedin github slack