By Alan A. A. Donovan and Brian W. Kernighan

Preface

The goals of language were to be

  • expressive

  • efficient in both compilation and execution

  • effective in writing reliable and robust programs

Go has become popular as a replacement for untyped scripting languages because it is faster and leads to fewer crashes due to unexpected type errors.

It is especially well suited for building infrastructure like networked servers or tools for programmers, but as a general purpose language it finds use in many areas like e.g. mobile applications or machine learning.

Origins

Go is influenced by the languages C, Oberon and communicating sequential processes

The most important influence from C is the emphasis on programs that compile to efficient machine code and cooperate naturally with the abstractions of the operating system further it’s expression syntax, control-flow statements, basic data types, call-by-value parameter passing and pointers.

Oberon influenced the syntax for packages, imports and method declarations.

Another lineage among Go’s ancestors is a sequence of little known research languages developed at Bell Labs (!), which are inspired by Tony Hoare’s communicating sequential processe.

The concept of lexical scope with nested functions is from Scheme.

The Go Project

The philosophy of the languages creators is to achieve simplicity. As Rob Pike put it: “complexity is multiplicative” - fixing a problem by making one part of system more complex slowly but surely adds complexity to other parts. Only through simplicity of design can a system remain stable, secure, and coherent as it grows.

Go encourages an awareness of computer system design. Especially the importance of locality in order achieve a good cpu cache hit ratio. Aggregate type (array and struct) hold their elements directly, requiring less storage and fewer allocations and pointer indirections than languages that use indirect fields.

Because the modern computer is a parallel machine, Go has lightweight threads or goroutines. These have a variable stack size which is initially small enough to make their creation cheap, so creating e.g. a million of them is practical.

1. Tutorial

This chapter shows some examples doing useful things as quckly as possible.

Unix Commands

As a teaser, the reader is shown how to implement some famous unix commands with very few lines of code. Among these are echo and curl.

Animated GIFs

Another example is to programmaticly create animated GIF images showing lissajous.

Web Server

With Go’s standard library, a web server can be created easily.

2. Program Structure

Go has 25 keywords:

break default func interface select
case defer go map struct
chan else goto package switch
const fallthrough if range type
continue for import return var

Built-ins:

Constants true false iota nil
   
Types int int8 int16 int32 int64
  uint uint8 uint16 uint32 uint64 uintptr
  float32 float64 complex128 complex64
  bool byte rune string error
   
Functions make len cap new append copy close delete
  complex real imag
  panic recover

3. Basic Data Types

A nice SVG is created using float64 calculations and fmt.Fprintf with this code:

3D

4. Composite Types

The first example computes a sha256 sum which is returned in an array of [32]byte.

But instead of working with arrays directly, go programmers use a slice most of the time.

JSON

It is shown how structs can be marshalled to json and vise versa. This is demonstrated with a command line tool doing a github search via the public REST API:

type IssuesSearchResult struct {
	TotalCount int `json:"total_count"`
	Items      []*Issue
}

type Issue struct {
	Number    int
	HTMLURL   string `json:"html_url"`
	Title     string
	State     string
	User      *User
	CreatedAt time.Time `json:"created_at"`
	Body      string    // in Markdown format
}

type User struct {
	Login   string
	HTMLURL string `json:"html_url"`
}

Templates

The text/template and html/template packages are used for rendering (hyper) text:

<h1>{{.TotalCount}} issues</h1>
<table>
<tr style='text-align: left'>
  <th>#</th>
  <th>State</th>
  <th>User</th>
  <th>Title</th>
</tr>
{{range .Items}}
<tr>
  <td><a href='{{.HTMLURL}}'>{{.Number}}</a></td>
  <td>{{.State}}</td>
  <td><a href='{{.User.HTMLURL}}'>{{.User.Login}}</a></td>
  <td><a href='{{.HTMLURL}}'>{{.Title}}</a></td>
</tr>
{{end}}
</table>

5. Functions

Functions are first-class values in Go. Like other values, functions have types and can be assigned to variables and passed to or returned by functions.

In the chapter there are some examples of traversing the abstract syntax tree of HTML which has been parsed with golang.org/x/net/html.

$ outline2 http://gopl.io | head
<html>
  <head>
    <meta>
    </meta>
    <title>
    </title>
  </head>
  <body>
    <table>
      <tbody>
        <tr>

Finding links:

$ findlinks3 http://gopl.io
http://www.amazon.com/dp/0134190440
http://www.barnesandnoble.com/w/1121601944
http://www.gopl.io/ch1.pdf
http://www.gopl.io/reviews.html
http://www.gopl.io/translations.html
http://www.gopl.io/errata.html

6. Methods

A Method is declared like an ordinary function declaration but with an extra parameter before the name. This parameter attaches the function to the type of the receiver.

I is ilustrated with a geometry example:

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

// same thing, but as a method of the Point type
func (p Point) Distance(q Point) float64 {
	return math.Hypot(q.X-p.X, q.Y-p.Y)
}

7. Interfaces

Interfaces are used for generalizations or abstractions about the behaviors of types. They are not tied to the details of particular implementation.

Eval

They are demonstrated using the sort package and implementing an expression evaluator with ast and parser.

XML

Another example is token based xml decoding using the package xml.

This is done using a stack to which the elements are pushed when another nested layer is started.

$ curl -s http://www.w3.org/TR/2006/REC-xml11-20060816/ | xmlselect div div h2
html body div div h2: 1 Introduction
html body div div h2: 2 Documents
html body div div h2: 3 Logical Structures
html body div div h2: 4 Physical Structures
html body div div h2: 5 Conformance
html body div div h2: 6 Notation
html body div div h2: A References
html body div div h2: B Definitions for Character Normalization
html body div div h2: C Expansion of Entity and Character References (Non-Normative)
html body div div h2: D Deterministic Content Models (Non-Normative)
html body div div h2: E Autodetection of Character Encodings (Non-Normative)
html body div div h2: F W3C XML Working Group (Non-Normative)
html body div div h2: G W3C XML Core Working Group (Non-Normative)
html body div div h2: H Production Notes (Non-Normative)
html body div div h2: I Suggestions for XML Names (Non-Normative)

8. Goroutines and Channels

With goroutines and channels Go offers fantastic support for concurrent programming.

FTP Server

One exercise is to implement an FTP server: exercise-8.2.

$ sudo ngrep -d any port 8000
interface: any
filter: (ip or ip6) and ( port 8000 )
#
T 127.0.0.1:60854 -> 127.0.0.1:8000 [AP]
  USER andre..                                                                                                                                                        
##
T 127.0.0.1:8000 -> 127.0.0.1:60854 [AP]
  230 User is andre..                                                                                                                                                 
##
T 127.0.0.1:60854 -> 127.0.0.1:8000 [AP]
  SYST..                                                                                                                                                              
#
T 127.0.0.1:8000 -> 127.0.0.1:60854 [AP]
  SYST.                                                                                                                                                               
##
T 127.0.0.1:60854 -> 127.0.0.1:8000 [AP]
  PORT 127,0,0,1,196,169..                                                                                                                                            
#
T 127.0.0.1:8000 -> 127.0.0.1:60854 [AP]
  200 PORT command successful.                                                                                                                                        
##
T 127.0.0.1:60854 -> 127.0.0.1:8000 [AP]
  LIST..                                                                                                                                                              
#
T 127.0.0.1:8000 -> 127.0.0.1:60854 [AP]
  150 Opening ASCII mode data connection for file list.                                                                                                               
#
T 127.0.0.1:8000 -> 127.0.0.1:60854 [AP]
  226 Transfer complete..                                                                                                                                             
#

Chat Server

How these play well together is shown with a simple chat server:

$ chat &
[1] 3879
$ nc localhost 8000
You are 127.0.0.1:60458
hi
127.0.0.1:60458: hi

9. Concurrency with Shared Variables

With the help of sync.Mutex a non blocking cache is implemented.