Go / Golang Cheat Sheet

May include word games. Let's Go!

#Getting Started with Go

What is Go?

Go is a compiled programming language, created by Google. It is known for being an alternative to C/C++, with an more readable syntax.

Hello World

package main

import "fmt"

func main() {
  fmt.Println("Hello World!")
}
Go needs the main-function. It gets executed when running the programm. A unique package name must be provided, there must be one main package.

Execute & Build

go run app.go  // run the code in dev mode
go build app.go // compiling
./app.go        // executing the build-file
The build-file, which can be executed without having Go installed, depends on the OS. On Windows, it will be an .exe.

#Variables

What is special about Variables in Go?

- In Go, there can no undefined or null values occur, when declaring variables.
- There is no need to declare a variable with a data type.
- We can declare multiple variables at once.
- There is a long way, providing the datatype when declaring, and a shorthand, using type inference for declaring.
- We can use var and const. Last one means constant, so changing the value of such a variable, will break the program.
A constant must have an initial value.

Declaring Variables

// Providing the value later
var name string 
name = "Max"

// Providing the value fist
var name string = "Max"

// Using type inference
name := "Max"
var width, height float32 = 2.5, 6.1
// or: 
width, height := 2.5, 6.1
fmt.Println(width) 	// 2.5
fmt.Println(height)	// 6.1
Using type inference, Go can guess the correct datatype for our variable. We can declare multiple variables at once.

Default value

var firstVar bool
fmt.Println(firstVar) // false

var firstVar string
fmt.Println(firstVar) // ""

var firstVar float64
fmt.Println(firstVar) // 0
                      
var firstVar int 
fmt.Println(firstVar) // 0
When providing a datatype for the variable when declaring, but leaving out the value, a default value will be applied

#Functions in Go

Function & Return

func add(x int, y int) int {
	return x + y
}

func main() {
	fmt.Println(add(5, 5))  // 10
}
The datatype stands after the variable name. The last 'int' is the datatype of the return-value.

Shorting the datatypes

func add(x, y int) int {
	return x + y
}
If both parameters have the same data type, we can use a shortcut.

Multiple Returns

func person(name string, age int) (string, int) {
	return name, age + 1
}

func main() {
	name, age := person("max", 22)
	fmt.Println(name, age)
	// max 23
}
A function in Go can return multiple things.

#Arrays

Basic Array

var ages [5]int 
fmt.Println(ages)
// [0 0 0 0 0]
Arrays can only hold one type of data. The first element always has the index of 0. They have a fixed size. Like variables in Go, they hold default values.

Adding some values to it

var ages [5]int
ages[0] = 21
ages[1] = 23
fmt.Println(ages)
// [21 23 0 0 0]
// the better way:
ages := [5]int{23, 21, 19, 23, 24}
fmt.Println(ages)
// [23 21 19 23 24]

Slices

ages := []int{23, 21, 19, 23, 24}
ages = append(ages, 27)
// append does not edit the existing slice. 
// It returns a new one.
fmt.Println(ages)
// [23 21 19 23 24 27]
Since arrays have a fixed number of elements, this is problem when we want to add something. By leaving out the number of elements, we initialize a slice.

Looping through an Array

ages := [3]int{23, 21, 19}
for index, value :=range ages {
    fmt.Println(index, value)
    // 0 23
    // 1 21
    // 2 19
}

#Conditionals

If-Else

if 5 > 3 {
    fmt.Println("5 > 3")
} else {
    fmt.Println("3 > 5")
}
There are now brackets in the syntax.

Else-if

if 5 > 5 {
    fmt.Println("5 > 3")
} else if 5 >= 5 {
    fmt.Println("Greater / equal")
} else {
    fmt.Println("3 > 5")
} 
Else-If provides another condition, and gets executed if the condition is true, and if is not getting executed.

Variables in if-else

if age := 9; age < 18 {
    fmt.Print("Not grown up")
 }
We can declare a variable within the syntax of an if-statement.

#For Loop

Which Loops exist?

In Go, there is only the for-loop available. But it can be used as while for example, as you can see in the examples.

for-loop

func main() {
	for i := 0; i < 5; i++ {
		fmt.Println(i)
	}
}
No () arround the content of the loop.

"While"-Loop in Go

for i := 0; i < 5; {
    fmt.Println(i)
    // endless prints
}

#Pointers

Using a Pointer

func main() {
    var age = 24
    var agePointer = &age
	fmt.Println(agePointer)
	// for example '0xc000016078'
}
The syntax with the '&' returns the memory address of the variable. Therefore, a Pointer holds a memory address.

Getting the value behind the Pointer

var age = 24
var agePointer = &age
fmt.Println(*agePointer) // 24
We can use the '*' syntax to read the value, saved in the memory with the memory address, the pointer is holding.

Changing values with Pointers

var age = 24
var agePointer = &age
*agePointer++
fmt.Println(*agePointer) // 25
Not only can we read out values from the memory, we can also change it through pointers.

#Map & Struct

Basic Struct

type person struct {
	name string
	age int
}
func main() {
	personMax := person{name: "Max", age: 21}
	fmt.Println(personMax) // { Max 21}
	fmt.Println(personMax.name) // Max
}

Basic Map

people := make(map[string]int)
people["Max"] = 23
people["Tom"] = 19

fmt.Println(people["Max"])
In the [] stands the type of the key, follwing is the type of the value.

Looping through a Map

people := make(map[string]int)
people["Max"] = 23
people["Tom"] = 19

for key, value := range people {
    fmt.Println(key, value)
    // Max 23
    // Tom 19
}