Golang Basics

Hello Gophers ... this is An Introduction to Golang

25 January 2021

Obed N Munoz

Cloud Software Engineer

Agenda

2

YaPL? - Yet another Programming Language?

3

The origin of The Gophermania

4

Who in the world is using Go?

5

Why should I care?

6

People want to code (Program Structure)

package main

import (
    "fmt"
)

func main() {
    topics := map[string]string{
        "easy":     "Program Structure",
        "inspired": "Basic and Composite types",
        "what?":    "Functions vs Methods",
        "cool":     "Goroutines",
        "crazy":    "Channels",
    }

    fmt.Printf("Let's have fun with: \n")
    for key, topic := range topics {
        fmt.Printf(" - \"%s\" which is: '%v' \n", topic, key)
    }
}
7

Program Structure (1/2)

package main

import (
    "fmt"
    "os"
)

func main() {
    var s, sep string
    for i := 1; i < len(os.Args); i++ {
        s += sep + os.Args[i]
        sep = " "
    }
    fmt.Println(s)
}
8

Program Structure (1/2)

func main() {
    counts := make(map[string]int)
    for _, filename := range os.Args[1:] {
        data, err := ioutil.ReadFile(filename)
        if err != nil {
            fmt.Fprintf(os.Stderr, "dup3: %v\n", err)
            continue
        }
        for _, line := range strings.Split(string(data), "\n") {
            counts[line]++
        }
    }
    for line, n := range counts {
        if n > 1 {
            fmt.Printf("%d\t%s\n", n, line)
        }
    }
}
9

Basic and Composite types (1/3)

10

Basic and Composite types (2/3)

const (
    width, height = 600, 320            // canvas size in pixels
    cells         = 100                 // number of grid cells
    xyrange       = 30.0                // axis ranges (-xyrange..+xyrange)
    xyscale       = width / 2 / xyrange // pixels per x or y unit
    zscale        = height * 0.4        // pixels per z unit
    angle         = math.Pi / 6         // angle of x, y axes (=30°)
)
var sin30, cos30 = math.Sin(angle), math.Cos(angle) // sin(30°), cos(30°)
11

Basic and Composite types (3/3)

letters := []string{"a", "b", "c", "d"}

func make([]T, len, cap) []T

var s []byte
s = make([]byte, 5, 5)
// s == []byte{0, 0, 0, 0, 0}
12

Let's code: Slices and Maps in Go

Follow the link that matches with your current class:

classify.obedmr.com/get-lab/ap-labs/go-slices-maps

classify.obedmr.com/get-lab/dc-labs/go-slices-maps

13

Functions vs Methods

Struct

type Point struct{ X, Y float64 }

// traditional function
func Distance(p, q Point) float64 {
    return math.Hypot(q.X-p.X, q.Y-p.Y)
}

Function

func Distance(p, q Point) float64 {
    return math.Hypot(q.X-p.X, q.Y-p.Y)
}

Method

func (p Point) Distance(q Point) float64 {
    return math.Hypot(q.X-p.X, q.Y-p.Y)
}
14

Let's code: Functions and Methods in Go

Follow the link that matches with your current class:

classify.obedmr.com/get-lab/ap-labs/go-functions-methods

classify.obedmr.com/get-lab/dc-labs/go-functions-methods

15

Goroutines

In Go, each concurrently executing activity is called a goroutine.

When a program starts, its only goroutine is the one that calls the main function. It's called the main goroutine.

f()       // call f(); wait for it to return
go f()    // create a new goroutine that calls f(); don't wait
16

Channels

If goroutines are the activities of a concurrent Go program, channels are the connections between them.

ch := make(chan int) // ch has type 'chan int'

ch <- x  // a send statement

x = <-ch // a receive expression in an assignment statement
<-ch     // a receive statement; result is discarded

close(ch) // To close a channel
17

Simple Web Server in Go

package main

import (
    "fmt"
    "log"
    "net/http"
)

func main() {
    http.HandleFunc("/", handler)
    log.Fatal(http.ListenAndServe("localhost:8000", nil))
}

// handler echo the Path component of the requested URL.
func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "URL.Path = %q\n", r.URL.Path)
}
18

What else?

19

Handy Stuff

20

Thank you

Obed N Munoz

Cloud Software Engineer

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.)