Basics

Maximilian Wurzer

Advisory IT Architect, IBM Deutschland

Types and data structures

2

Typing

3

Typing Examples

package main

import "fmt"

func main() {
    var myIntVar int = 23
    var myFloatVar float64 = 3.14
    var myString string = "Hello World"
    var myBool bool = true
    var myComplexVar complex128 = 5 + 3i

    fmt.Println("Integer:", myIntVar)
    fmt.Println("Float:", myFloatVar)
    fmt.Println("String:", myString)
    fmt.Println("My bool is", myBool)
    fmt.Println("My complex number is", myComplexVar)
}
4

Arrays, Slices and Maps

5

Arrays, Slices and Maps

package main

import "fmt"

func main() {
    b := [5]int{1, 2, 3, 4, 5}
    fmt.Println("array:", b)

    s := make([]string, 2)
    fmt.Println("empty slice:", s)
    s[0] = "a"
    s[1] = "b"
    s = append(s, "e", "f")
    fmt.Println("slice:", s)

    m := make(map[string]int)
    m["k1"] = 7
    m["k2"] = 13
    fmt.Println("map:", m)
    fmt.Println("map entry:", m["k1"])
}

Take a look at Slice Tricks

6

Pointers

package main

import "fmt"

func zeroval(ival int) {
    ival = 0
}

func zeroptr(iptr *int) {
    *iptr = 0
}

func main() {
    i := 1
    fmt.Println("initial:", i)

    zeroval(i)
    fmt.Println("zeroval:", i)

    zeroptr(&i)
    fmt.Println("zeroptr:", i, "| pointer:", &i)
}
7

Structs and Interfaces

8

Struct Example

package main

import "fmt"

type person struct {
    name string
    age  int
}

func newPerson(name string) *person {
    p := person{name: name}
    p.age = 42
    return &p
}

func main() {

    fmt.Println(person{"Bob", 20})
    fmt.Println(person{name: "Alice", age: 30})
    fmt.Println(newPerson("Jon"))
}
9

Interface Example

package main

import "fmt"

type geometry interface {
    area() float64
}

type rect struct {
    width, height float64
}

func (r rect) area() float64 {
    return r.width * r.height
}

func measure(g geometry) {
    fmt.Printf("Geo: %.2f | Area: %.2f", g, g.area())
}

func main() {
    r := rect{width: 3, height: 4}
    measure(r)
}
10

Visibility

There is no public, protected or private keyword.

Go does this by Naming-Conventions!

This applies to: Functions / Methods, Structs, Interfaces

Rules:

11

Control structures

12

if ... else if ... else

package main

import "fmt"

func main() {
    var number = 5

    if number < 0 {
        fmt.Println("Number is negative")
    } else if number > 0 {
        fmt.Println("Number is positive")
    } else {
        fmt.Println("Number is zero")
    }
}
13

switch ... case

package main

import "fmt"

func main() {
    var mood = "🙂"

    switch mood {
    case "🙂", "😀":
        fmt.Println("I'm happy")
    case "😞":
        fmt.Println("I'm disappointed")
    case "😢":
        fmt.Println("I'm sad")
    default:
        fmt.Println("No mood")
    }
}
14

Loops

package main

import "fmt"

func main() {
    var sum = 0
    for i := 0; i <= 3; i++ {
        sum += i
    }

    for sum < 100 {
        sum += 1
    }
    fmt.Println("Summe:", sum)

    // for { break }

    for index, value := range []string{"a", "b", "c", "d"} {
        fmt.Printf("Index: %d - Value: %s\n", index, value)
    }
}
15

Concurrency

16

Concurrency - Goroutines

Functions which are executed concurrent are called goroutine. These are defined as following (proc.go):

The main concepts are:
G - goroutine.
M - worker thread, or machine.
P - processor, a resource that is required to execute Go code.
    M must have an associated P to execute Go code, however it can be
    blocked or in a syscall w/o an associated P.

A goroutine is assigned to a Thread which is assigned to a physical CPU.

17

Concurrency - Goroutines Example

package main

import (
    "fmt"
    "time"
)

func f(from string) {
    for i := 0; i < 3; i++ {
        fmt.Println(from, ":", i)
        time.Sleep(time.Second)
    }
}

func main() {
    go f("goroutine")

    f("direct")

    fmt.Println("done")
}
18

Concurrency - Channels

Channels provide a way for two goroutines to communicate with each other and synchronize their execution.

19

Concurrency - Channels Example

package main

import "fmt"

func f(from chan string) {
    for i := 0; i < 3; i++ {
        from <- fmt.Sprint(i)
    }
}

func main() {
    messages := make(chan string)
    go f(messages)

    msg := <-messages
    fmt.Println("First:", msg)
    msg = <-messages
    fmt.Println("Second:", msg)
    msg = <-messages
    fmt.Println("Third:", msg)
}
20

Concurrency - Channels Direction & Buffer

package main

import "fmt"

func main() {
    messages := make(chan string, 2)

    messages <- "buffered"
    messages <- "channel"

    fmt.Println(<-messages)
    fmt.Println(<-messages)
}
21

Select

Wait on multiple channel operations:

22

Error handling

A simple built-in interface to implement for custom Error-Types:

type error interface {
    Error() string
}

Error Handling:

23

Error handling

package main

import "fmt"

func myDiv(a, b int) (*int, error) {
    if b == 0 {
        var err error = fmt.Errorf("You cannot divide by zero!")
        return nil, err
    } else {
        var result int = a / b
        return &result, nil
    }
}

func main() {
    result, err := myDiv(5, 0)
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Printf("The result is %d", result)
    }
}
24

Garbage Collection

25

Compilation - Under the hood

Go programs are compiled ahead of time to native machine code

  1. Parsing
  2. Type-checking and AST transformations
  3. Generic SSA (Static Single Assignment)
  4. Generating machine code
26

Compilation - Choose your target

One source - Many targets

Go is statically compiled down to its target’s native machine and mostly outperforms its virtualized (e.g. Java, Kotlin) and interpreted (e.g. JavaScript) counterparts.

27

Formatting

28

Go by Example

29

Thank you

Maximilian Wurzer

Advisory IT Architect, IBM Deutschland

Use the left and right arrow keys or click the left and right edges of the page to navigate between slides.
(Press 'H' or navigate to hide this message.)