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
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
- if else
- for loop
- conversion from int to string
- printing message
// 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
- channels are concurrency safe communication objects
- buffered channels limit size of channel (cannot be over-filled.
messageQueue := make(chan string, 10)
- over-reading or reading closed channel gives:
// fatal error: all goroutines are asleep - deadlock!
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
- archive
- tar: Package tar implements access to tar archives.
- zip: Package zip provides support for reading and writing ZIP archives.
- bufio: Package bufio implements buffered I/O. It wraps an io.Reader or io.Writer object, creating another object (Reader or Writer) that also implements the interface but provides buffering and some help for textual I/O.
- builtin: Package builtin provides documentation for Goβs predeclared identifiers.
- bytes: Package bytes implements functions for the manipulation of byte slices.
- compress
- bzip2: Package bzip2 implements bzip2 decompression.
- flate: Package flate implements the DEFLATE compressed data format, described in RFC 1951.
- gzip: Package gzip implements reading and writing of gzip format compressed files, as specified in RFC 1952.
- lzw: Package lzw implements the Lempel-Ziv-Welch compressed data format, described in T. A. Welch, βA Technique for High-Performance Data Compressionβ, Computer, 17(6) (June 1984), pp 8-19.
- zlib: Package zlib implements reading and writing of zlib format compressed data, as specified in RFC 1950.
- container
- heap: Package heap provides heap operations for any type that implements heap.Interface.
- list: Package list implements a doubly linked list.
- ring: Package ring implements operations on circular lists.
- context: Package context defines the Context type, which carries deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes.
- crypto: Package crypto collects common cryptographic constants.
- aes: Package aes implements AES encryption (formerly Rijndael), as defined in U.S. Federal Information Processing Standards Publication 197.
- cipher: Package cipher implements standard block cipher modes that can be wrapped around low-level block cipher implementations.
- des: Package des implements the Data Encryption Standard (DES) and the Triple Data Encryption Algorithm (TDEA) as defined in U.S. Federal Information Processing Standards Publication 46-3.
- dsa: Package dsa implements the Digital Signature Algorithm, as defined in FIPS 186-3.
- ecdsa: Package ecdsa implements the Elliptic Curve Digital Signature Algorithm, as defined in FIPS 186-3.
- ed25519: Package ed25519 implements the Ed25519 signature algorithm.
- elliptic: Package elliptic implements several standard elliptic curves over prime fields.
- hmac: Package hmac implements the Keyed-Hash Message Authentication Code (HMAC) as defined in U.S. Federal Information Processing Standards Publication 198.
- md5: Package md5 implements the MD5 hash algorithm as defined in RFC 1321.
- rand: Package rand implements a cryptographically secure random number generator.
- rc4: Package rc4 implements RC4 encryption, as defined in Bruce Schneierβs Applied Cryptography.
- rsa: Package rsa implements RSA encryption as specified in PKCS#1.
- sha1: Package sha1 implements the SHA-1 hash algorithm as defined in RFC 3174.
- sha256: Package sha256 implements the SHA224 and SHA256 hash algorithms as defined in FIPS 180-4.
- sha512: Package sha512 implements the SHA-384, SHA-512, SHA-512/224, and SHA-512/256 hash algorithms as defined in FIPS 180-4.
- subtle: Package subtle implements functions that are often useful in cryptographic code but require careful thought to use correctly.
- tls: Package tls partially implements TLS 1.2, as specified in RFC 5246, and TLS 1.3, as specified in RFC 8446.
- x509: Package x509 parses X.509-encoded keys and certificates.
- pkix: Package pkix contains shared, low level structures used for ASN.1 parsing and serialization of X.509 certificates, CRL and OCSP.
- database:
- sql: Package sql provides a generic interface around SQL (or SQL-like) databases.
- driver: Package driver defines interfaces to be implemented by database drivers as used by package sql.
- debug
- dwarf: Package dwarf provides access to DWARF debugging information loaded from executable files, as defined in the DWARF 2.0 Standard at http://dwarfstd.org/doc/dwarf-2.0.0.pdf
- elf: Package elf implements access to ELF object files.
- gosym: Package gosym implements access to the Go symbol and line number tables embedded in Go binaries generated by the gc compilers.
- macho: Package macho implements access to Mach-O object files.
- pe: Package pe implements access to PE (Microsoft Windows Portable Executable) files.
- plan9obj: Package plan9obj implements access to Plan 9 a.out object files.
- encoding: Package encoding defines interfaces shared by other packages that convert data to and from byte-level and textual representations.
- ascii85: Package ascii85 implements the ascii85 data encoding as used in the btoa tool and Adobeβs PostScript and PDF document formats.
- asn1: Package asn1 implements parsing of DER-encoded ASN.1 data structures, as defined in ITU-T Rec X.690.
- base32: Package base32 implements base32 encoding as specified by RFC 4648.
- base64: Package base64 implements base64 encoding as specified by RFC 4648.
- binary: Package binary implements simple translation between numbers and byte sequences and encoding and decoding of varints.
- csv: Package csv reads and writes comma-separated values (CSV) files.
- gob: Package gob manages streams of gobs - binary values exchanged between an Encoder (transmitter) and a Decoder (receiver).
- hex: Package hex implements hexadecimal encoding and decoding.
- json: Package json implements encoding and decoding of JSON as defined in RFC 7159.
- pem: Package pem implements the PEM data encoding, which originated in Privacy Enhanced Mail.
- xml: Package xml implements a simple XML 1.0 parser that understands XML name spaces.
- errors: Package errors implements functions to manipulate errors.
- expvar: Package expvar provides a standardized interface to public variables, such as operation counters in servers.
- flag: Package flag implements command-line flag parsing.
- fmt: Package fmt implements formatted I/O with functions analogous to Cβs printf and scanf.
- go:
- ast: Package ast declares the types used to represent syntax trees for Go packages.
- build: Package build gathers information about Go packages.
- constant: Package constant implements Values representing untyped Go constants and their corresponding operations.
- doc: Package doc extracts source code documentation from a Go AST.
- format: Package format implements standard formatting of Go source.
- importer: Package importer provides access to export data importers.
- parser: Package parser implements a parser for Go source files.
- printer: Package printer implements printing of AST nodes.
- scanner: Package scanner implements a scanner for Go source text.
- token: Package token defines constants representing the lexical tokens of the Go programming language and basic operations on tokens (printing, predicates).
- types: Package types declares the data types and implements the algorithms for type-checking of Go packages.
- hash: Package hash provides interfaces for hash functions.
- adler32: Package adler32 implements the Adler-32 checksum.
- crc32: Package crc32 implements the 32-bit cyclic redundancy check, or CRC-32, checksum.
- crc64: Package crc64 implements the 64-bit cyclic redundancy check, or CRC-64, checksum.
- fnv: Package fnv implements FNV-1 and FNV-1a, non-cryptographic hash functions created by Glenn Fowler, Landon Curt Noll, and Phong Vo.
- maphash: Package maphash provides hash functions on byte sequences.
- html: Package html provides functions for escaping and unescaping HTML text.
- template: Package template (html/template) implements data-driven templates for generating HTML output safe against code injection.
- image: Package image implements a basic 2-D image library.
- color: Package color implements a basic color library.
- palette: Package palette provides standard color palettes.
- draw: Package draw provides image composition functions.
- gif: Package gif implements a GIF image decoder and encoder.
- jpeg: Package jpeg implements a JPEG image decoder and encoder.
- png: Package png implements a PNG image decoder and encoder.
- index:
- suffixarray: Package suffixarray implements substring search in logarithmic time using an in-memory suffix array.
- io: Package io provides basic interfaces to I/O primitives.
- ioutil: Package ioutil implements some I/O utility functions.
- log: Package log implements a simple logging package.
- syslog: Package syslog provides a simple interface to the system log service.
- math: Package math provides basic constants and mathematical functions.
- big: Package big implements arbitrary-precision arithmetic (big numbers).
- bits: Package bits implements bit counting and manipulation functions for the predeclared unsigned integer types.
- cmplx: Package cmplx provides basic constants and mathematical functions for complex numbers.
- rand: Package rand implements pseudo-random number generators.
- mime: Package mime implements parts of the MIME spec.
- multipart: Package multipart implements MIME multipart parsing, as defined in RFC 2046.
- quotedprintable: Package quotedprintable implements quoted-printable encoding as specified by RFC 2045.
- net: Package net provides a portable interface for network I/O, including TCP/IP, UDP, domain name resolution, and Unix domain sockets.
- http: Package http provides HTTP client and server implementations.
- cgi: Package cgi implements CGI (Common Gateway Interface) as specified in RFC 3875.
- cookiejar: Package cookiejar implements an in-memory RFC 6265-compliant http.CookieJar.
- fcgi: Package fcgi implements the FastCGI protocol.
- httptest: Package httptest provides utilities for HTTP testing.
- httptrace: Package httptrace provides mechanisms to trace the events within HTTP client requests.
- httputil: Package httputil provides HTTP utility functions, complementing the more common ones in the net/http package.
- pprof: Package pprof serves via its HTTP server runtime profiling data in the format expected by the pprof visualization tool.
- mail: Package mail implements parsing of mail messages.
- rpc: Package rpc provides access to the exported methods of an object across a network or other I/O connection.
- jsonrpc: Package jsonrpc implements a JSON-RPC 1.0 ClientCodec and ServerCodec for the rpc package.
- smtp: Package smtp implements the Simple Mail Transfer Protocol as defined in RFC 5321.
- textproto: Package textproto implements generic support for text-based request/response protocols in the style of HTTP, NNTP, and SMTP.
- url: Package url parses URLs and implements query escaping.
- os: Package os provides a platform-independent interface to operating system functionality.
- exec: Package exec runs external commands.
- signal: Package signal implements access to incoming signals.
- user: Package user allows user account lookups by name or id.
- path: Package path implements utility routines for manipulating slash-separated paths.
- filepath: Package filepath implements utility routines for manipulating filename paths in a way compatible with the target operating system-defined file paths.
- plugin: Package plugin implements loading and symbol resolution of Go plugins.
- reflect: Package reflect implements run-time reflection, allowing a program to manipulate objects with arbitrary types.
- regexp: Package regexp implements regular expression search.
- syntax: Package syntax parses regular expressions into parse trees and compiles parse trees into programs.
- runtime: Package runtime contains operations that interact with Goβs runtime system, such as functions to control goroutines.
- cgo: Package cgo contains runtime support for code generated by the cgo tool.
- debug: Package debug contains facilities for programs to debug themselves while they are running.
- msan: pprof: Package pprof writes runtime profiling data in the format expected by the pprof visualization tool.
- race: Package race implements data race detection logic.
- trace: Package trace contains facilities for programs to generate traces for the Go execution tracer.
- sort: Package sort provides primitives for sorting slices and user-defined collections.
- strconv: Package strconv implements conversions to and from string representations of basic data types.
- strings: Package strings implements simple functions to manipulate UTF-8 encoded strings.
- sync: Package sync provides basic synchronization primitives such as mutual exclusion locks.
- atomic: Package atomic provides low-level atomic memory primitives useful for implementing synchronization algorithms.
- syscall: Package syscall contains an interface to the low-level operating system primitives.
- js: Package js gives access to the WebAssembly host environment when using the js/wasm architecture.
- testing: Package testing provides support for automated testing of Go packages.
- iotest: Package iotest implements Readers and Writers useful mainly for testing.
- quick: Package quick implements utility functions to help with black box testing.
- text
- scanner: Package scanner provides a scanner and tokenizer for UTF-8-encoded text.
- tabwriter: Package tabwriter implements a write filter (tabwriter.Writer) that translates tabbed columns in input into properly aligned text.
- template: Package template implements data-driven templates for generating textual output.
- parse: Package parse builds parse trees for templates as defined by text/template and html/template.
- time: Package time provides functionality for measuring and displaying time.
- unicode: Package unicode provides data and functions to test some properties of Unicode code points.
- utf16: Package utf16 implements encoding and decoding of UTF-16 sequences.
- utf8: Package utf8 implements functions and constants to support text encoded in UTF-8.
- unsafe: Package unsafe contains operations that step around the type safety of Go programs.
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 β.
- benchmarks β benchmarks to measure Go as it is developed.
- blog β blog.golang.org βs implementation.
- build β build.golang.org βs implementation.
- crypto β additional cryptography packages.
- debug β an experimental debugger for Go.
- image β additional imaging packages.
- mobile β experimental support for Go on mobile platforms.
- net β additional networking packages.
- perf β packages and tools for performance measurement, storage, and analysis.
- review β a tool for working with Gerrit code reviews.
- sync β additional concurrency primitives.
- sys β packages for making system calls.
- text β packages for working with text.
- time β additional time packages.
- tools β godoc, goimports, gorename, and other tools.
- tour β tour.golang.org βs implementation.
- exp β experimental and deprecated packages (handle with care; may change without warning).
References