Lightning Intro To Go
Sun Jan 22, 2017 · 2601 words

The Go Programming Language

Hello World in Go

package main
import "fmt"

func main() {
    fmt.Println("hello world")
}

Go Language and Runtime Feature Overview

Installing Go

#!/bin/bash

sudo -s
cd /usr/local/

export GOROOT_BOOTSTRAP=/usr/local/go-1.7.4

git clone https://go.googlesource.com/go
cd go/src && git checkout go1.8rc3
./all.bash

export PATH=$PATH:/usr/local/go/bin

IDEs

Installing VS Code with Go

Run/Build/Install command line example:

Packages and go get

Package Imports, and Visibility

Building, Testing, and Installing a Go package from command line

$ cd $GOPATH/src/github.com/knq/baseconv/
$ go build
$ go test -v
=== RUN   TestErrors
--- PASS: TestErrors (0.00s)
=== RUN   TestConvert
--- PASS: TestConvert (0.00s)
=== RUN   TestEncodeDecode
--- PASS: TestEncodeDecode (0.00s)
PASS
ok      github.com/knq/baseconv 0.002s
$ go install

Some Notes on Go’s Syntax/Design

Quick Syntax Primer

C vs Go, a simple comparison

#include <stdio.h>

int main(int argc, char **argv) {
    for (int i = 0; i < argc; i++) {
        printf(">> arg %d: %s\n", i, argv[i]);
    }
    return 0;
}
package main

import (
	"fmt"
	"os"
)

func main() {
	for i, a := range os.Args {
		fmt.Printf(">> arg %d: %s\n", i, a)
	}
}

Standard Types (builtin)

var b bool = false 
var s string = "" 
var b byte = 0 // alias for uint8

// -1 0
int   uint   
int8  uint8  
int16 uint16 
int32 uint32 
int64 uint64 

// 0.0  1.0i ...
float32 complex64
float64 complex128

// 'c'
rune // alias for int32

uintptr // an integer type that is large enough to hold the bit pattern of any pointer.

Expressions and Assignments

Expressions and Operators

Constants

Slices, Maps, Arrays

make and new

append, len, and reslicing

func

Control Statements

Control Statements

Control Statements

Variadic parameters

Type Declaration

Notes on Types

Type Receivers

About interface

Pointers, Interfaces, and nil

Goroutines and Channels

Goroutine and Channel example

package main

import (
    "fmt"
    "sync"
    "time"
)

func main() {
    var wg sync.WaitGroup

    c := make(chan int)
    for i := 0; i < 10; i++ {
        wg.Add(1)
        go func(z int) {
            defer wg.Done()
            time.Sleep(1 * time.Second)
            c <- z
        }(i)
    }

    wg.Add(1)
    go func() {
        defer wg.Done()
        for {
            select {
            case z := <-c:
                fmt.Printf(">> z: %d\n", z)
            case <-time.After(5 * time.Second):
                return
            }
        }
    }()

    wg.Wait()
    fmt.Println("done")
}

Handling Errors

Error Types

defer

Quick Overview of the Standard Library

```golang
import (
    "fmt"      // string formatting
    "strings"  // string manipulation
    "strconv"  // string conversion to standard types
    "io"       // system input/output package
    "sync"     // synchronization primitives
    "time"     // robust time handling/formatting
    "net/http" // http package supporting http servers and clients

    "database/sql"  // standardized sql interface
    "encoding/json" // json encoding/decoding (also packages for xml, csv, etc)

    // template libraries for text and html
    "text/template"
    "html/template" 

    // cryptographic libs
    "crypto/rsa"
    "crypto/elliptic"

    "reflect"       // go runtime introspection / reflection
    "regexp"        // regular expressions
)
// And many many many more!
```

What Go doesn’t have (and why this is a good thing)

Working Example

package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
)

func main() {
	// read from web
	res, err := http.Get("http://ifconfig.co/json")
	if err != nil {
		fmt.Fprintf(os.Stderr, "error: %v", err)
		os.Exit(1)
	}
	defer res.Body.Close()

	// read the body
	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		fmt.Fprintf(os.Stderr, "error: %v", err)
		os.Exit(1)
	}

	// decode json
	var vals map[string]interface{}
	err = json.Unmarshal(body, &vals)
	if err != nil {
		fmt.Fprintf(os.Stderr, "error: %v", err)
		os.Exit(1)
	}

	for k, v := range vals {
		fmt.Fprintf(os.Stdout, "%s: %v\n", k, v)
	}
}

back · he thought · he could · so he did · main