Go Cheat Sheet
Index
- Basic Syntax
- Operators
- Declarations
- Functions
- Built-in Types
- Type Conversions
- Packages
- Control structures
- Arrays, Slices, Ranges
- Maps
- Structs
- Pointers
- Interfaces
- Embedding
- Errors
- Concurrency
- Printing
- Reflection
- Snippets
Credits
Most example code taken from A Tour of Go, which is an excellent introduction to Go.
If you’re new to Go, do that tour. Seriously.
Go in a Nutshell
- Imperative language
- Statically typed
- Syntax tokens similar to C (but less parentheses and no semicolons) and the structure to Oberon-2
- Compiles to native code (no JVM)
- No classes, but structs with methods
- Interfaces
- No implementation inheritance. There’s type embedding, though.
- Functions are first class citizens
- Functions can return multiple values
- Has closures
- Pointers, but not pointer arithmetic
- Built-in concurrency primitives: Goroutines and Channels
Basic Syntax
Hello World
File hello.go
:1
2
3
4
5
6
7package main
import "fmt"
func main() {
fmt.Println("Hello Go")
}
$ go run hello.go
Operators
Arithmetic
Operator | Description | |
---|---|---|
+ |
addition | |
- |
subtraction | |
* |
multiplication | |
/ |
quotient | |
% |
remainder | |
& |
bitwise and | |
`\ | ` | bitwise or |
^ |
bitwise xor | |
&^ |
bit clear (and not) | |
<< |
left shift | |
>> |
right shift |
Comparison
Operator | Description |
---|---|
== |
equal |
!= |
not equal |
< |
less than |
<= |
less than or equal |
> |
greater than |
>= |
greater than or equal |
Logical
Operator | Description | ||
---|---|---|---|
&& |
logical and | ||
`\ | \ | ` | logical or |
! |
logical not |
Other
Operator | Description |
---|---|
& |
address of / create pointer |
* |
dereference pointer |
<- |
send / receive operator (see ‘Channels’ below) |
Declarations
Type goes after identifier!1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17var foo int // declaration without initialization
var foo int = 42 // declaration with initialization
var foo, bar int = 42, 1302 // declare and init multiple vars at once
var foo = 42 // type omitted, will be inferred
foo := 42 // shorthand, only in func bodies, omit var keyword, type is always implicit
const constant = "This is a constant"
// iota can be used for incrementing numbers, starting from 0
const (
_ = iota
a
b
c = 1 << iota
d
)
fmt.Println(a, b) // 1 2 (0 is skipped)
fmt.Println(c, d) // 8 16 (2^3, 2^4)
Functions
1 | // a simple function |
Functions As Values And Closures
1 | func main() { |
Variadic Functions
1 | func main() { |
Built-in Types
1 | bool |
Type Conversions
1 | var i int = 42 |
Packages
- Package declaration at top of every source file
- Executables are in package
main
- Convention: package name == last name of import path (import path
math/rand
=> packagerand
) - Upper case identifier: exported (visible from other packages)
- Lower case identifier: private (not visible from other packages)
Control structures
If
1 | func main() { |
Loops
1 | // There's only `for`, no `while`, no `until` |
Switch
1 | // switch statement |
Arrays, Slices, Ranges
Arrays
1 | var a [10]int // declare an int array with length 10. Array length is part of the type! |
Slices
1 | var a []int // declare a slice - similar to an array, but length is unspecified |
Operations on Arrays and Slices
len(a)
gives you the length of an array/a slice. It’s a built-in function, not a attribute/method on the array.
1 | // loop over an array/a slice |
Maps
1 | var m map[string]int |
Structs
There are no classes, only structs. Structs can have methods.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31// A struct is a type. It's also a collection of fields
// Declaration
type Vertex struct {
X, Y int
}
// Creating
var v = Vertex{1, 2}
var v = Vertex{X: 1, Y: 2} // Creates a struct by defining values with keys
var v = []Vertex{{1,2},{5,2},{5,5}} // Initialize a slice of structs
// Accessing members
v.X = 4
// You can declare methods on structs. The struct you want to declare the
// method on (the receiving type) comes between the the func keyword and
// the method name. The struct is copied on each method call(!)
func (v Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
// Call method
v.Abs()
// For mutating methods, you need to use a pointer (see below) to the Struct
// as the type. With this, the struct value is not copied for the method call.
func (v *Vertex) add(n float64) {
v.X += n
v.Y += n
}
Anonymous structs:
Cheaper and safer than using map[string]interface{}
.1
2
3point := struct {
X, Y int
}{1, 2}
Pointers
1 | p := Vertex{1, 2} // p is a Vertex |
Interfaces
1 | // interface declaration |
Embedding
There is no subclassing in Go. Instead, there is interface and struct embedding.
1 | // ReadWriter implementations must satisfy both Reader and Writer |
Errors
There is no exception handling. Functions that might produce an error just declare an additional return value of type Error
. This is the Error
interface:1
2
3type error interface {
Error() string
}
A function that might return an error:1
2
3
4
5
6
7
8
9
10
11func doStuff() (int, error) {
}
func main() {
result, err := doStuff()
if err != nil {
// handle error
} else {
// all is good, use result
}
}
Concurrency
Goroutines
Goroutines are lightweight threads (managed by Go, not OS threads). go f(a, b)
starts a new goroutine which runs f
(given f
is a function).
1 | // just a function (which can be later started as a goroutine) |
Channels
1 | ch := make(chan int) // create a channel of type int |
Channel Axioms
A send to a nil channel blocks forever
1
2
3var c chan string
c <- "Hello, World!"
// fatal error: all goroutines are asleep - deadlock!A receive from a nil channel blocks forever
1
2
3var c chan string
fmt.Println(<-c)
// fatal error: all goroutines are asleep - deadlock!A send to a closed channel panics
1
2
3
4
5var c = make(chan string, 1)
c <- "Hello, World!"
close(c)
c <- "Hello, Panic!"
// panic: send on closed channelA receive from a closed channel returns the zero value immediately
1
2
3
4
5
6
7
8var c = make(chan int, 2)
c <- 1
c <- 2
close(c)
for i := 0; i < 3; i++ {
fmt.Printf("%d ", <-c)
}
// 1 2 0
Printing
1 | fmt.Println("Hello, 你好, नमस्ते, Привет, ᎣᏏᏲ") // basic print, plus newline |
Reflection
Type Switch
A type switch is like a regular switch statement, but the cases in a type switch specify types (not values), and those values are compared against the type of the value held by the given interface value.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16func do(i interface{}) {
switch v := i.(type) {
case int:
fmt.Printf("Twice %v is %v\n", v, v*2)
case string:
fmt.Printf("%q is %v bytes long\n", v, len(v))
default:
fmt.Printf("I don't know about type %T!\n", v)
}
}
func main() {
do(21)
do("hello")
do(true)
}
Snippets
HTTP Server
1 | package main |