How About Go Language?

Well-written Go programs tend to be straightforward and sometimes a bit repetitive. There’s no inheritance, no aspect-oriented programming, no function overloading, and certainly no operator overloading. There’s no pattern matching, no named parameters, no exceptions.

Setting Up Go Environment

Installing Go

Archlinux

1
$ sudo pacman -S go

Mac

1
$ brew install golang

Windows

1
$ winget install -e --id GoLang.Go

Verify installed Go:

1
$ go version

The Go Workspace

environment variables:

  • $GOROOT

    GOROOT is a variable that defines where your Go SDK is located. You do not need to change this variable, unless you plan to use different Go versions.

  • $GOPATH

    GOPATH is a variable that defines the root of your workspace. By default, the workspace directory is a directory that is named go within your user home directory ($HOME/go for Linux and macOS, %USERPROFILE%/go for Windows). GOPATH stores your code base and all the files that are necessary for your development. GOPATH is the root of your workspace and contains the following folders:

    • src/: location of Go source code (for example, .go, .c, .g, .s).
    • pkg/: location of compiled package code (for example, .a).
    • bin/: location of compiled executable programs built by Go.
  • $GOBIN

    The directory where executables are installed using the go command. By default, $GOBIN is $GOPATH/bin (or $HOME/go/bin if GOPATH is not set). After installing, you will want to add this directory to your $PATH so you can use installed tools.

It’s a good idea to explicitly define GOPATH and to put the $GOPATH/bin directory in executable path makes it easier to run third-party tools installed via go install.

1
2
go env -w GOPATH=/somewhere/else
go env -w GOBIN=/somewhere/else/bin

The go Command

Print Go environment information:

1
2
go env -w GOPATH=/somewhere/else
go env -w GOBIN=/somewhere/else/bin

To unset a variable

1
2
go env -u GOPATH
go env -u GOBIN

Compile and run Go program:

1
go run [build flags] [-exec xprog] package [arguments...]

Compile packages and dependencies:

1
go build [-o output] [build flags] [packages]

Add dependencies to current module and install them:

1
go get [-t] [-u] [-v] [build flags] [packages]

Get resolves its command-line arguments to packages at specific module versions, updates go.mod to require those versions, and downloads source code into the module cache. Now, ‘go get’ is dedicated to adjusting dependencies in go.mod.

Compile and install packages and dependencies:

1
go install [build flags] [packages]

Executables are installed in the directory named by the GOBIN environment variable, which defaults to $GOPATH/bin or $HOME/go/bin if the GOPATH environment variable is not set. Executables in $GOROOT are installed in $GOROOT/bin or $GOTOOLDIR instead of $GOBIN.

When a version is specified, ‘go install’ runs in module-aware mode and ignores the go.mod file in the current directory.

Gofmt (reformat) package sources:

1
go fmt [-n] [-x] [packages]

There’s an enhanced version of go fmt available called goimports that also cleans up your import statements.

1
go install golang.org/x/tools/cmd/goimports@latest
1
goimports -l -w .

List packages or modules:

1
go list [-f format] [-json] [-m] [list flags] [build flags] [packages]

Report likely mistakes in packages:

1
go vet [build flags] [-vettool prog] [vet flags] [packages]

Module maintenance:

initialize new module in current directory

1
go mod init

add missing and remove unused modules

1
go mod tidy

download modules to local cache

1
go mod download   

Remove object files and cached files:

1
go clean [clean flags] [build flags] [packages]

remove all downloaded modules, including unpacked source code of versioned dependencies.

1
go clean -modcache

Test packages:

1
go test [build/test flags] [packages] [build/test flags & test binary flags]

Linting

Linting:

1
go install golang.org/x/lint/golint@latest
1
golint ./...

golangci-lint combines go lint, go vet, and an ever-increasing set of other code quality tools. Once it is installed, you run golangci-lint with the command:

1
golangci-lint run

Tools

  • Visual Studio Code

    extension tools: The Delve debugger, and gopls

  • Goland

  • The Go Playground

1
go install golang.org/x/tools/gopls@latest

Makefiles

GOPROXY

Installation

1
2
3
4
$ # Use it programmatically (RECOMMENDED).
$ go get github.com/goproxy/goproxy
$ # Or use our minimalist CLI implementation.
$ go install github.com/goproxy/goproxy/cmd/goproxy@latest

Go 1.13 and above (RECOMMENDED)

1
go env -w GOPROXY=https://goproxy.io,direct
1
go env -w GOPROXY=http://localhost:8080,direct

macOS or Linux

1
export GOPROXY=https://goproxy.io,direct
1
2
3
4
5
# add environment to your profile
echo "export GOPROXY=https://goproxy.io,direct" >> ~/.profile && source ~/.profile

# if your terminal is zsh,type the command below
echo "export GOPROXY=https://goproxy.io,direct" >> ~/.zshrc && source ~/.zshrc

Windows

1
$env:GOPROXY = "https://goproxy.io,direct"
1
2
3
4
5
1. Right click This PC -> Properties -> Advanced system settings -> Environment Variables
2. Click "New" in Environment Variables
3. Input Variable Name: “GOPROXY”
4. Input Variable Value: “https://goproxy.io,direct”
5. Click "OK", save your settings.

Alternative Proxy

1
2
https://goproxy.io
https://goproxy.cn

Lexical elements

Comments

1
2
3
4
5
// single line comments

/* 
multiple line commonts
*/

Semicolons

The Semicolon Insertion Rule:

The lexer uses a simple rule to insert semicolons automatically:

  • If the last token before a newline is an identifier (which includes words like int and float64), a basic literal such as a number or string constant, or one of the tokens

    1
    
    break continue fallthrough return ++ -- ) }
    

    the lexer always inserts a semicolon after the token. This could be summarized as, “if the newline comes after a token that could end a statement, insert a semicolon”.

  • A semicolon can also be omitted immediately before a closing brace, so a statement such as

    1
    
    go func() { for { dst <- <-src } }()
    

​ needs no semicolons.

One consequence of the semicolon insertion rules is that you cannot put the opening brace of a control structure (if, for, switch, or select) on the next line.

1
2
3
if i < f() {
    g()
}
1
2
3
4
if i < f()  // wrong!
{           // wrong!
    g()
}

literals

Literals in Go are untyped, they can interact with any variable that’s compatible with the literal.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
42                 // Integer literals
0b101010           // 0b prefix for binary, equal to 42 
0o52               // 0O prefix for octal, equal to 42 
0x2A               // 0x prefix for hexadecimal, equal to 42 

72.40              // Floating-point literals

0123i              // Imaginary literals for complex numbers

'\''               // Rune literals represent characters and are surrounded by single quotes.

`abc`              // backquotes for raw string literals same as "abc"
"\""               // double quotes to create interpreted string literals same as `"`        

Primitive Types

Boolean

Variables of bool type can have one of two predeclared constant values: true or false.

1
2
var flag bool // no value assigned, set to false
var isAwesome = true

Numeric

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
uint8       
uint16     
uint32      
uint64     unsigned 64-bit

int8        
int16       
int32       
int64      signed 64-bit integers

float32     
float64     

complex64  
complex128  

byte        alias for uint8
rune        alias for int32
1
var val int64 = 42

The int, uint, and uintptr types are usually 32 bits wide on 32-bit systems and 64 bits wide on 64-bit systems. When you need an integer value you should use int unless you have a specific reason to use a sized or unsigned integer type.

Explicit conversions are required when different numeric types are mixed in an expression or assignment.

Using int64 and uint64 in a library function and let callers use type conversions to pass values in. In those cases, you need to write a separate function for every integer type.

The result of an integer division is an integer; if you want to get a floating point result, you need to use a type conversion to make your integers into floating point numbers.

Arithmetic operators:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
+    sum                    integers, floats, complex values, strings
-    difference             integers, floats, complex values
*    product                integers, floats, complex values
/    quotient               integers, floats, complex values
%    remainder              integers

&    bitwise AND            integers
|    bitwise OR             integers
^    bitwise XOR            integers
&^   bit clear (AND NOT)    integers

<<   left shift             integer << integer >= 0
>>   right shift            integer >> integer >= 0

Operators with assignment statements:

1
2
3
4
5
6
+=    &=
-=    |=
*=    ^=
/=    <<=
%=    >>=
      &^=

Go has integer types called byte and rune that are aliases for uint8 and int32 data types, respectively. In Go, there is no char data type. It uses byte and rune to represent character values. The byte data type represents ASCII characters while the rune data type represents a more broader set of Unicode characters that are encoded in UTF-8 format.

The default type for character values is rune, which means, if we don’t declare a type explicitly when declaring a variable with a character value, then Go will infer the type as rune.

1
2
var myLetter = 'R'                // rune: 82
var anotherLetter byte = 'B'      // byte: 66

String

Strings are immutable: once created, it is impossible to change the contents of a string.

1
2
3
4
5
6
7
var str1 = "hello "
var str2 = "world"
var msg = str1 + str2        // Arithmetic operators: + also applies to strings.
var cnt = len(msg)           // the built-in function len 

var char = msg[0]            // A string's bytes can be accessed by integer indices
fmt.Print(string(char))      // String characters are bytes, explicit convert to String for print

Zero values

Variables declared without an explicit initial value are given their zero value.

The zero value is:

  • 0 for numeric types,
  • false for the boolean type, and
  • "" (the empty string) for strings.

Type conversions

The expression T(v) converts the value v to the type T.

1
2
3
i := 42
f := float64(i)
u := uint(f)

Unlike in C, in Go assignment between items of different type requires an explicit conversion.

An explicit conversion is an expression of the form T(x) where T is a type and x is an expression that can be converted to type T.

1
2
3
4
var x int = 10
var y float64 = 30.2
var z float64 = float64(x) + y
var d int = x + int(y)
1
2
var a = '\n'            // rune
var b = byte(a)         // byte

If the type starts with the operator * or <-, or if the type starts with the keyword func and has no result list, it must be parenthesized when necessary to avoid ambiguity:

1
2
3
4
5
6
7
8
*Point(p)        // same as *(Point(p))
(*Point)(p)      // p is converted to *Point
<-chan int(c)    // same as <-(chan int(c))
(<-chan int)(c)  // c is converted to <-chan int
func()(x)        // function signature func() x
(func())(x)      // x is converted to func()
(func() int)(x)  // x is converted to func() int
func() int(x)    // x is converted to func() int (unambiguous)

Another Go type cannot be treated as a boolean. In fact, no other type can be converted to a bool, implicitly or explicitly. If you want to convert from another data type to boolean, you must use one of the comparison operators (==, !=, >, <, <=, or >=). For example, to check if variable x is equal to 0, the code would be x == 0. If you want to check if string s is empty, use s == “”.

Variables

Variables

The var statement declares a list of variables; as in function argument lists, the type is last.

1
var c, python, java bool

Variables with initializers

If an initializer is present, the type can be omitted

1
var c, python, java = true, false, "no!"

Short variable declarations

Inside a function, the := short assignment statement can be used in place of a var declaration with implicit type.

Outside a function, every statement begins with a keyword (var, func, and so on) and so the :=construct is not available.

A variable is a storage location for holding a value. Go assigns a zero value (default value) to any variable that is declared but not assigned a value.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
var i int
var U, V, W float64
var k = 0
var x, y float32 = -1, -2
var (
	i       int
	u, v, s = 2.0, 3.0, "bar"
)
var re, im = complexSqrt(-1)
var _, found = entries[name]  // map lookup; only interested in "found"

If a type is present, each variable is given that type. Otherwise, each variable is given the type of the corresponding initialization value in the assignment. If that value is an untyped constant, it is first implicitly converted to its default type; if it is an untyped boolean value, it is first implicitly converted to type bool. The predeclared value nil cannot be used to initialize a variable with no explicit type.

1
2
3
4
var d = math.Sin(0.5)  // d is float64
var i = 42             // i is int
var t, ok = x.(T)      // t is T, ok is bool
var n = nil            // illegal

Implementation restriction: A compiler may make it illegal to declare a variable inside a function body if the variable is never used.

Short variable declarations

A short variable declaration uses the syntax:

1
IdentifierList := ExpressionList

Unlike regular variable declarations, a short variable declaration may redeclare variables with the same type.

Short variable declarations may appear only inside functions. Declaring a variable at package level, must use var.

Package-level variables whose values change are a bad idea. As a general rule, only declare variables in the package block that are effectively immutable.

It is an error to declare a variable without using it. The blank identifier provides a workaround.

1
var _ = identifier  // For debugging; delete when done.

Type inference

When declaring a variable without specifying an explicit type, the variable’s type is inferred from the value on the right hand side.

When the right hand side contains an untyped numeric constant, the new variable may be an int, float64, or complex128 depending on the precision of the constant:

1
2
3
i := 42           // int
f := 3.142        // float64
g := 0.867 + 0.5i // complex128

Constant

Constants are declared like variables, but with the const keyword.

Constants can be character, string, boolean, or numeric values.

Constants cannot be declared using the := syntax.

There are boolean constants, rune constants, integer constants, floating-point constants, complex constants, and string constants. Rune, integer, floating-point, and complex constants are collectively called numeric constants.

Typed Constants

Numeric constants are high-precision values.

1
2
const Pi float64 = 3.14159265358979323846
const u, v float32 = 0, 3    // u = 0.0, v = 3.0

Untyped Constants

An untyped constant takes the type needed by its context.

If you are giving a name to a mathematical constant that could be used with multiple numeric types, then keep the constant untyped.

If the expression values are untyped constants, the declared constants remain untyped and the constant identifiers denote the constant values.

1
2
3
4
5
6
const zero = 0.0         // untyped floating-point constant
const (
	size int64 = 1024
	eof        = -1  // untyped integer constant
)
const a, b, c = 3, 4, "foo"  // a = 3, b = 4, c = "foo", untyped integer and string constants

const in Go is very limited. Constants in Go are a way to give names to literals. They can only hold values that the compiler can figure out at compile time. Go doesn’t provide a way to specify that a value calculated at runtime is immutable.

Naming

Go requires identifier names to start with a letter or underscore, and the name can contain numbers, underscores, and letters.

Package names

By convention, packages are given lower case, single-word names; there should be no need for underscores or mixedCaps.

Don’t use the import . notation, which can simplify tests that must run outside the package they are testing, but should otherwise be avoided.

Getters

If you have a field called owner (lower case, unexported), the getter method should be called Owner (upper case, exported), not GetOwner.

1
2
3
4
owner := obj.Owner()
if owner != user {
    obj.SetOwner(user)
}

Interface names

By convention, one-method interfaces are named by the method name plus an -er suffix or similar modification to construct an agent noun: Reader, Writer, Formatter, CloseNotifier etc.

If your type implements a method with the same meaning as a method on a well-known type, give it the same name and signature; call your string-converter method String not ToString.

Constants names

In many languages, constants are always written in all uppercase letters, with words separated by underscores. Go does not follow this pattern. This is because Go uses the case of the first letter in the name of a package-level declaration to determine if the item is accessible outside the package.

MixedCaps

The convention in Go is to use MixedCaps or mixedCaps rather than underscores to write multiword names.

People will use the first letter of a type as the variable name (for example, i for integers, f for floats, b for -booleans). When you define your own types, similar patterns apply.

Composite Types

Pointers

Go has pointers. A pointer holds the memory address of a value.

The type *T is a pointer to a T value. Its zero value is nil.

1
var p *int
1
2
i := 42
p = &i   // The & operator generates a pointer to its operand.

The * operator denotes the pointer’s underlying value. This is known as “dereferencing” or “indirecting”.

1
2
fmt.Println(*p) // read i through the pointer p
*p = 21         // set i through the pointer p

Unlike C, Go has no pointer arithmetic.

Pointer references to variables of a given type, called the base type of the pointer. The value of an uninitialized pointer is nil.

Reference:

For an operand x of type T, the address operation &x generates a pointer of type *T to x.

Dereference

* is also used to dereference pointer variables.

Array

The type [n]T is an array of n values of type T.

1
var a [10]int

Arrays cannot be resized.

Slices

Strings and Runes and Bytes

An array has a fixed size. A slice, on the other hand, is a dynamically-sized, flexible view into the elements of an array.

The type []T is a slice with elements of type T.

A slice is formed by specifying two indices, a low and high bound, separated by a colon, which is a half-open range:

1
a[low : high]

Slices are like references to arrays

A slice does not store any data, it just describes a section of an underlying array.

Changing the elements of a slice modifies the corresponding elements of its underlying array.

Slice literals

A slice literal is like an array literal without the length.

This creates an array, then builds a slice that references it:

1
[]bool{true, true, false}

Slice defaults

When slicing, you may omit the high or low bounds to use their defaults instead.

The default is zero for the low bound and the length of the slice for the high bound.

Slice length and capacity

A slice has both a length and a capacity.

The length of a slice is the number of elements it contains.

The capacity of a slice is the number of elements in the underlying array, counting from the first element in the slice.

The length and capacity of a slice s can be obtained using the expressions len(s) and cap(s).

You can extend a slice’s length by re-slicing it, provided it has sufficient capacity.

Nil slices

The zero value of a slice is nil.

A nil slice has a length and capacity of 0 and has no underlying array.

Creating a slice with make

Slices can be created with the built-in make function; this is how you create dynamically-sized arrays.

The make function allocates a zeroed array and returns a slice that refers to that array:

1
a := make([]int, 5)  // len(a)=5

To specify a capacity, pass a third argument to make:

1
2
3
4
b := make([]int, 0, 5) // len(b)=0, cap(b)=5

b = b[:cap(b)] // len(b)=5, cap(b)=5
b = b[1:]      // len(b)=4, cap(b)=4

Slices of slices

Slices can contain any type, including other slices.

1
2
3
4
5
board := [][]string{
	[]string{"_", "_", "_"},
	[]string{"_", "_", "_"},
	[]string{"_", "_", "_"},
}

Appending to a slice

It is common to append new elements to a slice, and so Go provides a built-in append function.

1
func append(s []T, vs ...T) []T
1
2
var s []int
s = append(s, 0)

Range

The range form of the for loop iterates over a slice or map.

When ranging over a slice, two values are returned for each iteration. The first is the index, and the second is a copy of the element at that index.

Range continued

You can skip the index or value by assigning to _.

1
2
3
4
pow := make([]int, 10)
for _, value := range pow {
	fmt.Printf("%d\n", value)
}

Exercise: Slices

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
func Pic(dx, dy int) [][]uint8 {
    var ret [][]unit8
	for i:=0; i!=dy; i++ {
	    row := make([]uint8, dy)
		for j, _ := range row {
		    row[i] = uint8(j)
	    }
		ret.append(row)
	}
	return ret
}

Maps

A map maps keys to values.

The zero value of a map is nil. A nil map has no keys, nor can keys be added.

The make function returns a map of the given type, initialized and ready for use.

1
2
3
4
type Vertex struct {
	Lat, Long float64
}
var m = make(map[string]Vertex)

Map literals

Map literals are like struct literals, but the keys are required.

1
2
3
4
5
6
7
8
var m = map[string]Vertex{
	"Bell Labs": Vertex{
		40.68433, -74.39967,
	},
	"Google": Vertex{
		37.42202, -122.08408,
	},
}

Map literals continued

If the top-level type is just a type name, you can omit it from the elements of the literal.

1
2
3
4
var m = map[string]Vertex{
	"Bell Labs": {40.68433, -74.39967},
	"Google":    {37.42202, -122.08408},
}

Mutating Maps

1
2
3
m[key] = elem    // Insert or update an element
elem = m[key]    // Retrieve an element
delete(m, key)   // Delete an element

Test that a key is present with a two-value assignment:

1
elem, ok := m[key]

If key is in m, ok is true. If not, ok is false.

If key is not in the map, then elem is the zero value for the map’s element type.

Exercise: Maps

1
2
3
4
5
6
7
func WordCount(s string) map[string]int {
    ret := make(map[string]int)
    for _, v := range strings.Fields(s) {
	    ret[v] += 1
	}
	return ret
}

Structs

A struct is a collection of fields.

1
2
3
4
type Vertex struct {
	X int
	Y int
}

Struct Fields

Struct fields are accessed using a dot.

1
2
v := Vertex{1, 2}
v.X = 4

Pointers to structs

Struct fields can be accessed through a struct pointer. The language permits us instead to write just p.X, without the explicit dereference.

Struct Literals

A struct literal denotes a newly allocated struct value by listing the values of its fields. You can list just a subset of fields by using the Name:syntax.

The special prefix & returns a pointer to the struct value.

1
2
3
4
5
6
7
type Vertex struct {
	X, Y int
}
v1 = Vertex{1, 2}  // has type Vertex
v2 = Vertex{X: 1}  // Y:0 is implicit
v3 = Vertex{}      // X:0 and Y:0
p  = &Vertex{1, 2} // has type *Vertex

Function

Interface

Map

Channel

Control Flow

For

Go has only one looping construct, the for loop.

Unlike other languages like C, Java, or JavaScript there are no parentheses surrounding the three components of the for statement and the braces { } are always required.

1
2
3
for i := 0; i < 10; i++ {
	sum += i
}

The init and post statements are optional.

1
2
3
4
sum := 1
for ; sum < 1000; {
	sum += sum
}

For is Go’s “while”

1
2
3
for sum < 1000 {
	sum += sum
}

Forever

If you omit the loop condition it loops forever, so an infinite loop is compactly expressed.

1
2
for {
}

If

Go’s if statements need not be surrounded by parentheses ( ) but the braces { } are required.

1
2
if x < 0 {
}

If with a short statement

The if statement can start with a short statement to execute before the condition. Variables declared by the statement are only in scope until the end of the if.

1
2
if v := math.Pow(x, n); v < lim {
}

If and else

Variables declared inside an if short statement are also available inside any of the else blocks.

1
2
3
4
5
if v := math.Pow(x, n); v < lim {
	return v
} else {
	fmt.Printf("%g >= %g\n", v, lim)
}

Switch

A switch statement is a shorter way to write a sequence of if - else statements. It runs the first case whose value is equal to the condition expression.

Go only runs the selected case, not all the cases that follow. In effect, the break statement that is needed at the end of each case in other languages is provided automatically in Go. Another important difference is that Go’s switch cases need not be constants, and the values involved need not be integers.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
func main() {
	fmt.Print("Go runs on ")
	switch os := runtime.GOOS; os {
	case "darwin":
		fmt.Println("OS X.")
	case "linux":
		fmt.Println("Linux.")
	default:
		// freebsd, openbsd,
		// plan9, windows...
		fmt.Printf("%s.\n", os)
	}
}

Switch evaluation order

Switch cases evaluate cases from top to bottom, stopping when a case succeeds.

Switch with no condition

Switch without a condition is the same as switch true.

This construct can be a clean way to write long if-then-else chains.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
func main() {
	t := time.Now()
	switch {
	case t.Hour() < 12:
		fmt.Println("Good morning!")
	case t.Hour() < 17:
		fmt.Println("Good afternoon.")
	default:
		fmt.Println("Good evening.")
	}
}

Defer

A defer statement defers the execution of a function until the surrounding function returns.

The deferred call’s arguments are evaluated immediately, but the function call is not executed until the surrounding function returns.

1
2
3
4
func main() {
	defer fmt.Println("world")
	fmt.Println("hello")
}

Stacking defers

Deferred function calls are pushed onto a stack. When a function returns, its deferred calls are executed in last-in-first-out order.

Functions

Function values

Functions are values too. They can be passed around just like other values.

Function values may be used as function arguments and return values.

1
2
3
4
5
6
7
func compute(fn func(float64, float64) float64) float64 {
	return fn(3, 4)
}
hypot := func(x, y float64) float64 {
	return math.Sqrt(x*x + y*y)
}
fmt.Println(compute(hypot))

Function closures

Go functions may be closures. A closure is a function value that references variables from outside its body. The function may access and assign to the referenced variables; in this sense the function is “bound” to the variables.

1
2
3
4
5
6
7
func adder() func(int) int {
	sum := 0
	return func(x int) int {
		sum += x
		return sum
	}
}

Exercise: Fibonacci closure

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
func fibonacci() func() int {
    x, y := 0, 1
    return func() int {
	    x, y = y, x + y
		return x
	}
}

func main() {
	f := fibonacci()
	for i := 0; i < 10; i++ {
		fmt.Println(f())
	}
}

A function can take zero or more arguments. Notice that the type comes after the argument name.

When two or more consecutive named function parameters share a type, you can omit the type from all but the last.

1
func add(x, y int) int {}

Multiple results

A function can return any number of results.

1
2
3
func swap(x, y string) (string, string) {
	return y, x
}

Named return values

Go’s return values may be named. These names should be used to document the meaning of the return values.

A return statement without arguments returns the named return values. This is known as a “naked” return.

Naked return statements should be used only in short functions. They can harm readability in longer functions.

1
2
3
4
5
func split(sum int) (x, y int) {
	x = sum * 4 / 9
	y = sum - x
	return
}

Methods

A method is a function with a receiver. A method declaration associates the method with the receiver’s base type.

The receiver type must be a defined type T or a pointer to a defined type T.

1
2
3
4
5
6
7
8
type run struct {
	Parameters params
	Results    modules.Result
}

func (r *run) pingIcmp() (err error) {
	return
}

Go does not have classes. However, you can define methods on types.

A method is a function with a special receiver argument.

The receiver appears in its own argument list between the func keyword and the method name.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
type Vertex struct {
	X, Y float64
}

// the Abs method has a receiver of type Vertex named v.
func (v Vertex) Abs() float64 {
	return math.Sqrt(v.X*v.X + v.Y*v.Y)
}

func main() {
	v := Vertex{3, 4}
	fmt.Println(v.Abs())
}

Methods are functions

Remember: a method is just a function with a receiver argument.

1
2
3
4
// written as a regular function with no change in functionality
func Abs(v Vertex) float64 {
	return math.Sqrt(v.X*v.X + v.Y*v.Y)
}

You can declare a method on non-struct types, too.

You can only declare a method with a receiver whose type is defined in the same package as the method. You cannot declare a method with a receiver whose type is defined in another package (which includes the built-in types such as int).

1
2
3
4
5
6
7
8
type MyFloat float64

func (f MyFloat) Abs() float64 {
	if f < 0 {
		return float64(-f)
	}
	return float64(f)
}

Pointer receivers

You can declare methods with pointer receivers.

This means the receiver type has the literal syntax *T for some type T. (Also, T cannot itself be a pointer such as *int.)

For example, the Scale method here is defined on *Vertex.

Methods with pointer receivers can modify the value to which the receiver points. Since methods often need to modify their receiver, pointer receivers are more common than value receivers.

With a value receiver, the method operates on a copy of the original value.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
type Vertex struct {
	X, Y float64
}

func (v Vertex) Abs() float64 {
	return math.Sqrt(v.X*v.X + v.Y*v.Y)
}

func (v *Vertex) Scale(f float64) {
	v.X = v.X * f
	v.Y = v.Y * f
}

func main() {
	v := Vertex{3, 4}
	v.Scale(10)
	fmt.Println(v.Abs())
}

Pointers and functions

The Abs and Scale methods rewritten as functions.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
type Vertex struct {
	X, Y float64
}

func Abs(v Vertex) float64 {
	return math.Sqrt(v.X*v.X + v.Y*v.Y)
}

func Scale(v *Vertex, f float64) {
	v.X = v.X * f
	v.Y = v.Y * f
}

func main() {
	v := Vertex{3, 4}
	Scale(&v, 10)
	fmt.Println(Abs(v))
}

Methods and pointer indirection

Comparing the previous two programs, you might notice that functions with a pointer argument must take a pointer:

1
2
3
var v Vertex
ScaleFunc(v, 5)  // Compile error!
ScaleFunc(&v, 5) // OK

while methods with pointer receivers take either a value or a pointer as the receiver when they are called:

1
2
3
4
var v Vertex
v.Scale(5)  // OK
p := &v
p.Scale(10) // OK

For the statement v.Scale(5), even though v is a value and not a pointer, the method with the pointer receiver is called automatically. That is, as a convenience, Go interprets the statement v.Scale(5) as (&v).Scale(5) since the Scale method has a pointer receiver.

Methods and pointer indirection (2)

The equivalent thing happens in the reverse direction.

1
2
3
4
5
6
func (v Vertex) Abs() float64 {
	return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
func AbsFunc(v Vertex) float64 {
	return math.Sqrt(v.X*v.X + v.Y*v.Y)
}

Functions that take a value argument must take a value of that specific type:

1
2
3
var v Vertex
fmt.Println(AbsFunc(v))  // OK
fmt.Println(AbsFunc(&v)) // Compile error!

while methods with value receivers take either a value or a pointer as the receiver when they are called:

1
2
3
4
var v Vertex
fmt.Println(v.Abs()) // OK
p := &v
fmt.Println(p.Abs()) // OK

In this case, the method call p.Abs() is interpreted as (*p).Abs().

Choosing a value or pointer receiver

There are two reasons to use a pointer receiver.

The first is so that the method can modify the value that its receiver points to.

The second is to avoid copying the value on each method call. This can be more efficient if the receiver is a large struct.

In general, all methods on a given type should have either value or pointer receivers, but not a mixture of both.

Interfaces

An interface type is defined as a set of method signatures.

A value of interface type can hold any value that implements those methods.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
type Abser interface {
	Abs() float64
}

func main() {
	var a Abser
	f := MyFloat(-math.Sqrt2)
	v := Vertex{3, 4}

	a = f  // a MyFloat implements Abser
	a = &v // a *Vertex implements Abser

	fmt.Println(a.Abs())
}

type MyFloat float64

func (f MyFloat) Abs() float64 {
	if f < 0 {
		return float64(-f)
	}
	return float64(f)
}

type Vertex struct {
	X, Y float64
}

func (v *Vertex) Abs() float64 {
	return math.Sqrt(v.X*v.X + v.Y*v.Y)
}

Interfaces are implemented implicitly

A type implements an interface by implementing its methods. There is no explicit declaration of intent, no “implements” keyword.

Implicit interfaces decouple the definition of an interface from its implementation, which could then appear in any package without prearrangement.

Interface values

Under the hood, interface values can be thought of as a tuple of a value and a concrete type:

1
(value, type)

An interface value holds a value of a specific underlying concrete type.

Calling a method on an interface value executes the method of the same name on its underlying type.

Interface values with nil underlying values

If the concrete value inside the interface itself is nil, the method will be called with a nil receiver.

In some languages this would trigger a null pointer exception, but in Go it is common to write methods that gracefully handle being called with a nil receiver (as with the method M in this example.)

Note that an interface value that holds a nil concrete value is itself non-nil.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
type I interface {
	M()
}

type T struct {
	S string
}

func (t *T) M() {
	if t == nil {
		fmt.Println("<nil>")
		return
	}
	fmt.Println(t.S)
}

func main() {
	var i I

	var t *T
	i = t
	describe(i)
	i.M()

	i = &T{"hello"}
	describe(i)
	i.M()
}

func describe(i I) {
	fmt.Printf("(%v, %T)\n", i, i)
}

Nil interface values

A nil interface value holds neither value nor concrete type.

Calling a method on a nil interface is a run-time error because there is no type inside the interface tuple to indicate which concrete method to call.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
type I interface {
	M()
}

func main() {
	var i I
	describe(i)
	i.M()
}

func describe(i I) {
	fmt.Printf("(%v, %T)\n", i, i)
}

The empty interface

The interface type that specifies zero methods is known as the empty interface:

1
interface{}

An empty interface may hold values of any type. (Every type implements at least zero methods.)

Empty interfaces are used by code that handles values of unknown type. For example, fmt.Printtakes any number of arguments of type interface{}.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
func main() {
	var i interface{}
	describe(i)

	i = 42
	describe(i)

	i = "hello"
	describe(i)
}

func describe(i interface{}) {
	fmt.Printf("(%v, %T)\n", i, i)
}

Type assertions

A type assertion provides access to an interface value’s underlying concrete value.

1
t := i.(T)

This statement asserts that the interface value iholds the concrete type T and assigns the underlying T value to the variable t.

If i does not hold a T, the statement will trigger a panic.

To test whether an interface value holds a specific type, a type assertion can return two values: the underlying value and a boolean value that reports whether the assertion succeeded.

1
t, ok := i.(T)

If i holds a T, then t will be the underlying value and ok will be true.

If not, ok will be false and t will be the zero value of type T, and no panic occurs.

Note the similarity between this syntax and that of reading from a map.

examples:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package main

type DatabaseConfig struct{}
type BaseSecretConfig struct{}

type AuthConfig struct{}

func (c *AuthConfig) DBConfig() {}

func (c *AuthConfig) SecretConfig() {}

type DatabaseConfigProvider interface {
	DBConfig() *DatabaseConfig
}

type SecretManagerConfigProvider interface {
	SecretConfig() *BaseSecretConfig
}

func setup(config interface{}) {
	if provider, ok := config.(DatabaseConfigProvider); ok {
	    _ = provider.DBConfig()
	}
	if provider, ok := config.(SecretManagerConfigProvider); ok {
	    _ = provider.SecretConfig()
	}
}

func main() {
   var config AuthConfig
   setup(config)
}

Type switches

A type switch is a construct that permits several type assertions in series.

A type switch is like a regular switch statement, but the cases in a type switch specify types (not values), and those values are compared against the type of the value held by the given interface value.

1
2
3
4
5
6
7
8
switch v := i.(type) {
case T:
    // here v has type T
case S:
    // here v has type S
default:
    // no match; here v has the same type as i
}

The declaration in a type switch has the same syntax as a type assertion i.(T), but the specific type T is replaced with the keyword type.

This switch statement tests whether the interface value i holds a value of type T or S. In each of the T and S cases, the variable v will be of type T or S respectively and hold the value held by i. In the default case (where there is no match), the variable v is of the same interface type and value as i.

Stringers

One of the most ubiquitous interfaces is Stringer defined by the fmt package.

1
2
3
type Stringer interface {
    String() string
}

A Stringer is a type that can describe itself as a string. The fmt package (and many others) look for this interface to print values.

Exercise: Stringers

Make the IPAddr type implement fmt.Stringer to print the address as a dotted quad.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
type IPAddr [4]byte

func (ip IPAddr) String() string {
    return fmt.Sprintf("%v.%v.%v.%v", ip[0], ip[1], ip[2], ip[3])
}

func main() {
	hosts := map[string]IPAddr{
		"loopback":  {127, 0, 0, 1},
		"googleDNS": {8, 8, 8, 8},
	}
	for name, ip := range hosts {
		fmt.Printf("%v: %v\n", name, ip)
	}
}

Errors

Go programs express error state with error values.

The error type is a built-in interface similar to fmt.Stringer:

1
2
3
type error interface {
    Error() string
}

(As with fmt.Stringer, the fmt package looks for the error interface when printing values.)

**Functions often return an error value, and calling code should handle errors by testing whether the error equals nil**.

1
2
3
4
5
6
i, err := strconv.Atoi("42")
if err != nil {
    fmt.Printf("couldn't convert number: %v\n", err)
    return
}
fmt.Println("Converted integer:", i)

A nil error denotes success; a non-nil error denotes failure.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
type MyError struct {
	When time.Time
	What string
}

func (e *MyError) Error() string {
	return fmt.Sprintf("at %v, %s",
		e.When, e.What)
}

func run() error {
	return &MyError{
		time.Now(),
		"it didn't work",
	}
}

func main() {
	if err := run(); err != nil {
		fmt.Println(err)
	}
}

Exercise: Errors

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
func (e ErrNegativeSqrt) Error() string {
    return fmt.Sprintf("cannot Sqrt negative number: %v", float64(e))
}
    
func Sqrt(x float64) (float64, error) {
	return 0, nil
}

func Sqrt(x float64) (float64, error) {
	if x < 0 {
		return 0, ErrNegativeSqrt(x)
	}
	z := 1.0
	for {
		if math.Abs(z-(z-(z*z-x)/(z*2))) < 0.00000000000001 {
			return z, nil
		} else {
			z = z - (z*z-x)/(z*2)
		}
	}
}

func main() {
	fmt.Println(Sqrt(2))
	fmt.Println(Sqrt(-2))
}

Readers

The io package specifies the io.Reader interface, which represents the read end of a stream of data.

The Go standard library contains many implementations of these interfaces, including files, network connections, compressors, ciphers, and others.

The io.Reader interface has a Read method:

1
func (T) Read(b []byte) (n int, err error)

Read populates the given byte slice with data and returns the number of bytes populated and an error value. It returns an io.EOF error when the stream ends.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
func main() {
	r := strings.NewReader("Hello, Reader!")

	b := make([]byte, 8)
	for {
	    // consumes its output 8 bytes at a time
		n, err := r.Read(b)
		fmt.Printf("n = %v err = %v b = %v\n", n, err, b)
		fmt.Printf("b[:n] = %q\n", b[:n])
		if err == io.EOF {
			break
		}
	}
}

Exercise: Readers

Implement a Reader type that emits an infinite stream of the ASCII character 'A'.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
type MyReader struct{}

func (r MyReader) Read(b []byte) (int, error) {
    for i, _ := range b {
	    b[i] = 'A'
	}
	return len(b), nil
}

func main() {
	reader.Validate(MyReader{})
}

Exercise: rot13Reader

A common pattern is an io.Reader that wraps another io.Reader, modifying the stream in some way.

For example, the gzip.NewReader function takes an io.Reader (a stream of compressed data) and returns a *gzip.Reader that also implements io.Reader (a stream of the decompressed data).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
type rot13Reader struct {
	r io.Reader
}

func rot13(x byte) byte {
    capital := x >= 'A' && x <= 'Z'
    if !capital && (x < 'a' || x > 'z') {
        return x // Not a letter
    }

    x += 13
    if capital && x > 'Z' || !capital && x > 'z' {
        x -= 26
    }
    return x
}

func (r13 *rot13Reader) Read(b []byte) (int, error) {
    n, err := r13.r.Read(b)
    for i := 0; i <= n; i++ {
        b[i] = rot13(b[i])
    }
    return n, err
}

func main() {
	s := strings.NewReader("Lbh penpxrq gur pbqr!")
	r := rot13Reader{s}
	io.Copy(os.Stdout, &r)
}

Images

Package image defines the Image interface:

1
2
3
4
5
6
7
package image

type Image interface {
    ColorModel() color.Model
    Bounds() Rectangle
    At(x, y int) color.Color
}

Note: the Rectangle return value of the Boundsmethod is actually an image.Rectangle, as the declaration is inside package image.

(See the documentation for all the details.)

The color.Color and color.Model types are also interfaces, but we’ll ignore that by using the predefined implementations color.RGBA and color.RGBAModel. These interfaces and types are specified by the image/color package

Exercise: Images

Remember the picture generator you wrote earlier? Let’s write another one, but this time it will return an implementation of image.Image instead of a slice of data.

Define your own Image type, implement the necessary methods, and call pic.ShowImage.

Bounds should return a image.Rectangle, like image.Rect(0, 0, w, h).

ColorModel should return color.RGBAModel.

At should return a color; the value v in the last picture generator corresponds to color.RGBA{v, v, 255, 255} in this one.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
type Image struct{
    width int
    height int
}

func (img Image) ColorModel() color.Model {
    return color.RGBAModel
}

func (img Image) Bounds() image.Rectangle {
    return image.Rect(0, 0, img.width, img.height)
}

func (img Image) At(x, y int) color.Color {
    img_func := func(x, y int) uint8 {
        //return uint8(x*y)
        //return uint8((x+y) / 2)
        return uint8(x^y)
    }
    v := img_func(x, y)
    return color.RGBA{v, v, 255, 255}
}

func main() {
	m := Image{256, 64}
	pic.ShowImage(m)
}

Modules

Repositories, Modules, and Packages

Dependency tracking using go.mod

The go mod init command initializes and writes a new go.mod file in the current directory, in effect creating a new module rooted at the current directory.

1
$ go mod init [module-path]

By default, the go list command lists the packages that are used in your project. The -m flag changes the output to list the modules instead.

1
$ go list -m all

go mod tidy ensures that the go.mod file matches the source code in the module. It adds any missing module requirements necessary to build the current module’s packages and dependencies, and it removes requirements on modules that don’t provide any relevant packages. It also adds any missing entries to go.sum and removes unnecessary entries.

1
$ go mod tidy [-e] [-v] [-go=version] [-compat=version]

Whenever you run any go command that requires dependencies (such as go run, go build, go test, or even go list). The go.sum will be created.

Packages

Creating a Package

The package clause consists of the keyword package and the name for the package. The package clause is always the first nonblank, noncomment line in a Go source file. It defines the package to which the file belongs.

1
package PackageName

A single unimported package called the main package is the special package to be a staring point.

By convention, the package name is the same as the last element of the import path.

Import

A package’s exported identifiers (an identifier is the name of a variable, coonstant, type, function, method, or a field in a struct) cannot be accessed from another current package without an import statement.

An identifier may be exported to permit access to it from another package. An identifier is exported if both:

  • the first character of the identifier’s name is a Unicode uppercase letter (Unicode character category Lu); and
  • the identifier is declared in the package block or it is a field name or method name.

The import path must be specified when importing from anywhere besides the standard library. The import path is built by appending the path to the package within the module to the module path. By convention, the package name is the same as the last element of the import path.

How exported identifiers is accessed for the various types of import declaration:

1
2
3
4
5
Import declaration          Local name of Sin

import   "lib/math"         math.Sin
import m "lib/math"         m.Sin
import . "lib/math"         Sin

To import a package solely for its side-effects (initialization), use the blank identifier as explicit package name:

1
import _ "lib/math"

It is good style to use the factored import statement:

1
2
3
4
import (
	"fmt"
	"math"
)

Call code in an external package

  1. Visit pkg.go.dev and search package, such as quote
  2. Locate and click selection package
  3. note that package quote is included in the rsc.io/quote module
1
2
3
4
5
6
7
8
9
package main

import "fmt"

import "rsc.io/quote"

func main() {
    fmt.Println(quote.Go())
}

Input and Output

Goroutines and Channels

concurrent progrmming model: CSP (communicationg sequential processes)

Goroutines

A goroutine is a lightweight thread managed by the Go runtime.

1
go f(x, y, z)

starts a new goroutine running

1
f(x, y, z)

The evaluation of f, x, y, and z happens in the current goroutine and the execution of f happens in the new goroutine.

Goroutines run in the same address space, so access to shared memory must be synchronized.

Channels

Channels are a typed conduit through which you can send and receive values with the channel operator, <-.

1
2
3
4
ch := make(chan int)    // create channel 
ch <- v    // Send v to channel ch.
v := <-ch  // Receive from ch, and
           // assign value to v.

By default, sends and receives block until the other side is ready. This allows goroutines to synchronize without explicit locks or condition variables.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
func sum(s []int, c chan int) {
	sum := 0
	for _, v := range s {
		sum += v
	}
	c <- sum // send sum to c
}

func main() {
	s := []int{7, 2, 8, -9, 4, 0}

	c := make(chan int)
	go sum(s[:len(s)/2], c)
	go sum(s[len(s)/2:], c)
	x, y := <-c, <-c // receive from c

	fmt.Println(x, y, x+y)
}

Buffered Channels

Channels can be buffered. Provide the buffer length as the second argument to make to initialize a buffered channel:

1
ch := make(chan int, 100)

Sends to a buffered channel block only when the buffer is full. Receives block when the buffer is empty.

The capacity of buffered channels can be obtained using the expressions cap().

1
cap(ch)

Range and Close

A sender can close a channel to indicate that no more values will be sent.

1
close(ch)

Receivers can test whether a channel has been closed by assigning a second parameter to the receive expression: after

1
v, ok := <-ch

ok is false if there are no more values to receive and the channel is closed.

The loop for i := range c receives values from the channel repeatedly until it is closed.

Note: Only the sender should close a channel, never the receiver. Sending on a closed channel will cause a panic.

Another note: Channels aren’t like files; you don’t usually need to close them. Closing is only necessary when the receiver must be told there are no more values coming, such as to terminate a range loop.

Select

The select statement lets a goroutine wait on multiple communication operations.

A select blocks until one of its cases can run, then it executes that case. It chooses one at random if multiple are ready.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
func fibonacci(ch, quit chan int) {
	x, y := 0, 1
	for {
		select {
		case ch <- x:
			x, y = y, x+y
		case <- quit:
			fmt.Println("quit")
			return
		}
	}
}
func main() {
	ch := make(chan int)
	quit := make(chan int)
	go func() {
		for i := 0; i < 10; i++ {
			fmt.Println(<-ch)
		}
		quit <- 0
	}()
	fibonacci(ch, quit)
}

Default Selection

The default case in a select is run if no other case is ready. Use a default case to try a send or receive without blocking

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
tick := time.Tick(100 * time.Millisecond)
boom := time.After(500 * time.Millisecond)
for {
    select {
    case <-tick:
        fmt.Println("tick.")
    case <-boom:
        fmt.Println("BOOM!")
        return
    default:
        fmt.Println("    .")
        time.Sleep(50 * time.Millisecond)
    }
}

Concurrency with Shared Variables

concurrent progrmming model: shared memory multithreading

sync.Mutex

Make sure only one goroutine can access a variable at a time to avoid conflicts. This concept is called mutual exclusion, and the conventional name for the data structure that provides it is mutex.

Go’s standard library provides mutual exclusion with sync.Mutex and its two methods:

  • Lock
  • Unlock

Use defer to ensure the mutex will be unlocked.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// SafeCounter is safe to use concurrently.
type SafeCounter struct {
	mu sync.Mutex
	v  map[string]int
}

// Inc increments the counter for the given key.
func (c *SafeCounter) Inc(key string) {
	c.mu.Lock()
	// Lock so only one goroutine at a time can access the map c.v.
	c.v[key]++
	c.mu.Unlock()
}

// Value returns the current value of the counter for the given key.
func (c *SafeCounter) Value(key string) int {
	c.mu.Lock()
	// Lock so only one goroutine at a time can access the map c.v.
	defer c.mu.Unlock()
	return c.v[key]
}

func main() {
	c := SafeCounter{v: make(map[string]int)}
	for i := 0; i < 1000; i++ {
		go c.Inc("somekey")
	}

	time.Sleep(time.Second)
	fmt.Println(c.Value("somekey"))
}

Reflection

FieldByName

1
2
3
4
5
6
7
8
type user struct {
    firstName string
    lastName  string
}
u := user{firstName: "John", lastName: "Doe"}
s := reflect.ValueOf(u)

fmt.Println("Name:", s.FieldByName("firstName"))    // Name: John

What Now?

You can get started by installing Go.

Once you have Go installed, the Go Documentation is a great place to continue. It contains references, tutorials, videos, and more.

To learn how to organize and work with Go code, read How to Write Go Code.

If you need help with the standard library, see the package reference. For help with the language itself, you might be surprised to find the Language Spec is quite readable.

To further explore Go’s concurrency model, watch Go Concurrency Patterns (slides) and Advanced Go Concurrency Patterns (slides) and read the Share Memory by Communicating codewalk.

To get started writing web applications, watch A simple programming environment (slides) and read the Writing Web Applications tutorial.

The First Class Functions in Go codewalk gives an interesting perspective on Go’s function types.

The Go Blog has a large archive of informative Go articles.

Visit the Go home page for more.

Reference

The go Command

The Go Programming Language Specification

Build Systems With Go

a-tour-of-go

standard-library

Debugging-with-Delve

generate-model-structs-from-database

glide

gopm

material

package_download

quick-start

web-dev-with-gin-needed

gin

go-get-golang-x-solution.md

good-at.md

gorm.md

modules.md

photoprism.md