A Tour of Go
Who? Ian Yang
From? Intridea Inc.
When? March 27, 2013
Slide 2
Slide 2 text
Contents
1 How to Write Go Code
2 A Tour of Go
Hello World
Functions
Variables
Control Statements
Data Structures
Methods and Interfaces
Concurrency
3 Continue Reading
Slide 3
Slide 3 text
Outline
1 How to Write Go Code
2 A Tour of Go
Hello World
Functions
Variables
Control Statements
Data Structures
Methods and Interfaces
Concurrency
3 Continue Reading
Go Package
All go files in a directory
Do not find files recursively
Slide 9
Slide 9 text
Go Package
All go files in a directory
Do not find files recursively
All files declare the same
package
Slide 10
Slide 10 text
Package Search
Search by import path
Slide 11
Slide 11 text
Package Search
Search by import path
Import path is relative directory
path
Slide 12
Slide 12 text
Package Search
Search by import path
Import path is relative directory
path
Search paths in GOPATH one by
one
Slide 13
Slide 13 text
Package Search
Search by import path
Import path is relative directory
path
Search paths in GOPATH one by
one
pkg first, then src
Slide 14
Slide 14 text
Executable
A package that declares package
main
Slide 15
Slide 15 text
Executable
A package that declares package
main
Installed into bin
Slide 16
Slide 16 text
Executable
A package that declares package
main
Installed into bin
Run func main
Slide 17
Slide 17 text
Toolkit
go build compile package
Slide 18
Slide 18 text
Toolkit
go build compile package
go install compile and install
Slide 19
Slide 19 text
Toolkit
go build compile package
go install compile and install
go test run tests in *_test.go
Slide 20
Slide 20 text
Toolkit
go build compile package
go install compile and install
go test run tests in *_test.go
go get install remote packages
Slide 21
Slide 21 text
Toolkit
go build compile package
go install compile and install
go test run tests in *_test.go
go get install remote packages
go help manual
Slide 22
Slide 22 text
Outline
1 How to Write Go Code
2 A Tour of Go
Hello World
Functions
Variables
Control Statements
Data Structures
Methods and Interfaces
Concurrency
3 Continue Reading
Slide 23
Slide 23 text
A Tour of Go
Let's rock with the online tour
tour.golang.org
Slide 24
Slide 24 text
Outline
1 How to Write Go Code
2 A Tour of Go
Hello World
Functions
Variables
Control Statements
Data Structures
Methods and Interfaces
Concurrency
3 Continue Reading
Slide 25
Slide 25 text
Hello World
1
package main
2
3
import "fmt"
4
5
func main() {
6
fmt.Println("Hello ,␣World")
7
}
Slide 26
Slide 26 text
package
Only package main is executable
Must be the same in directory
Default name when imported
Convention: same with the last
element of the import path
Slide 27
Slide 27 text
If we do not follow
the convention,
foo/greeting.go
1
package bar // <-- import path is foo
2
import "fmt"
3
func Greeting () {
4
fmt.Println("Hello ,␣World")
5
}
Slide 28
Slide 28 text
User will be confused.
hello/main.go
1
package main
2
import "foo"
3
func main() {
4
bar.Greeting ()
5
}
in group
1
import (
2
"fmt"
3
"math"
4
)
5
import (
6
fmt "fmt"
7
m "math"
8
)
Slide 31
Slide 31 text
Exported names
a name is exported if it begins
with a capital letter.
global var, const, type and func
Slide 32
Slide 32 text
General Declaration
Rules
type after variable
type is optional if it can be
deduced
Slide 33
Slide 33 text
Outline
1 How to Write Go Code
2 A Tour of Go
Hello World
Functions
Variables
Control Statements
Data Structures
Methods and Interfaces
Concurrency
3 Continue Reading
Slide 34
Slide 34 text
func
1 func sum(x int , y int) int {
2 return x + y;
3 }
Slide 35
Slide 35 text
func Cont.
You can omit the type if two or
more consecutive parameters
share a type.
1 func sum(x, y int) int {
2 return x + y;
3 }
Slide 36
Slide 36 text
func Multiple results
1 func swap(x, y string) (string , string) {
2 return y, x;
3 }
4 func main() {
5 x, y := swap("hello", "world")
6 }
Slide 37
Slide 37 text
Comma OK pattern
1 func main() {
2 m := map[string]string{
3 "foo": "bar"
4 }
5
6 if name , ok := m["name"]; ok {
7 fmt.Println(name)
8 }
9 }
func Named results
1 func Sqrt(f float64) (result float64 , err
error) {
2 if f < 0 {
3 err = ...
4 } else {
5 result = ...
6 }
7 return
8 }
Slide 40
Slide 40 text
Outline
1 How to Write Go Code
2 A Tour of Go
Hello World
Functions
Variables
Control Statements
Data Structures
Methods and Interfaces
Concurrency
3 Continue Reading
Slide 41
Slide 41 text
Variables
The var statement declares a
list of variables.
1 var a, b, c int
Slide 42
Slide 42 text
Variables Cont.
Cross multiple lines
1 var (
2 a int
3 b string
4 )
Slide 43
Slide 43 text
Variables initializer
1 var x, y, z = true , "foo", 3.14
Slide 44
Slide 44 text
Variables initializer
Cont.
Cross multiple lines
1 var (
2 a int = 10
3 b = "foo"
4 )
Slide 45
Slide 45 text
Short Assignment
Inside function, := short
assignment can be used in place
of var with implicit type.
1 func main() {
2 a, b, c := "foo", true , 3.14
3 }
Slide 46
Slide 46 text
Short Assignment
At least one variable is newly
declared in current scope
1 func parse(path string) (config map[sring]
sring , err error) {
2 file , err := os.Open(path)
3 data := make ([]byte , 100)
4 count , err := file.Read(data)
5 ...
6 }
Slide 47
Slide 47 text
Variables Scope
block scope (except if)
parameters and named results
are in the scope of function
block
var, := hide the variable in
parent scope
Primitive Types Cont.
byte alias of uint8
rune Unicode code, alias of int32
float32 float64
complex64 complex128
Slide 50
Slide 50 text
Constants
like var, but use const
character, string, boolean, or
numeric values.
1 const Pi = 3.14
2 func main() {
3 const World = "world"
4 }
Slide 51
Slide 51 text
First class func
1 add = func(x, y int) int {
2 return x + y
3 }
4 fmt.Println(add(10, 20)) // => 30
Slide 52
Slide 52 text
Closure
1 func adder () func(int) int {
2 sum := 0
3 return func(int x) int {
4 sum += x
5 return sum
6 }
7 }
Slide 53
Slide 53 text
Outline
1 How to Write Go Code
2 A Tour of Go
Hello World
Functions
Variables
Control Statements
Data Structures
Methods and Interfaces
Concurrency
3 Continue Reading
Slide 54
Slide 54 text
for
no ( )
{ } are required
1 sum := 0
2 for i := 1; i <= 10; i++ {
3 sum += i
4 }
Slide 55
Slide 55 text
for Pitfalls
There is no comma operator
++ and -- are statements
1 for a,b := 0,0; a<10; a,b = a+1,b+1 {
2 ...
3 }
Slide 56
Slide 56 text
for is while
1 sum , i := 0, 1
2 for i <= 10 {
3 sum += i
4 }
Slide 57
Slide 57 text
forever
1 for {
2 serve(<-req)
3 }
Slide 58
Slide 58 text
if
no ( )
{ } are required
1 func abs(x int) int {
2 if x < 0 {
3 return -x
4 }
5 return x
6 }
Slide 59
Slide 59 text
if initializer
1 if name , err := m["name"]; ok {
2 fmt.Println(name)
3 }
Variable declared in initializer is
visible in all branches
Slide 60
Slide 60 text
Switch
1 switch os := runtime.GOOS; os {
2 case "darwin":
3 fmt.Println("OS␣X.")
4 case "linux":
5 fmt.Println("Linux.")
6 default:
7 fmt.Printf("%s.", os) // freebsd , ...
8 }
9 }
Slide 61
Slide 61 text
Outline
1 How to Write Go Code
2 A Tour of Go
Hello World
Functions
Variables
Control Statements
Data Structures
Methods and Interfaces
Concurrency
3 Continue Reading
Slide 62
Slide 62 text
struct
1 type Vertex struct {
2 X int
3 Y int
4 }
5 var origin = Vertex{0, 0}
6 var xUnit = Vertex{X:1}
7 var yUnit = Vertex{Y:1}
Slide 63
Slide 63 text
struct fields
1 type Vertex struct { X, Y int }
2 func main() {
3 v := Vertex {100, 200}
4 v.X = 300
5 fmt.Println(v.X, v.Y) // => 300 200
6 }
Slide 64
Slide 64 text
Pointers
1 type Vertex struct { X, Y int }
2 func main() {
3 v := Vertex {100, 200}
4 var p *Vertex = &v
5 p.X = 300
6 fmt.Println(v.X, v.Y) // => 300 200
7 }
Slide 65
Slide 65 text
new
1 var p *T = new(T)
2 p: = new(T)
Slide 66
Slide 66 text
Slices
1 p := []int{2, 3, 5, 7, 11, 13}
2
3 for i := 0; i < len(p); i++ {
4 fmt.Printf("p[%d]␣=␣%d\n", i, p[i])
5 }
range
1 prime := []int{2,3,5,7,11,13}
2 for i, value := range pow {
3 fmt.Printf("prime [%d]=%d\n", i, value)
4 }
Slide 74
Slide 74 text
range
1 pow := make ([]int , 10)
2 for i := range pow { // only key
3 pow[i] = 1 << uint(i)
4 }
5 for _, value := range pow { // only value
6 fmt.Printf("%d\n", value)
7 }
Slide 75
Slide 75 text
map
1 type Vertex struct {
2 Lat , Long float64
3 }
4
5 var m = map[string]Vertex{
6 "Bell␣Labs": Vertex {40.68433 , -74.39967} ,
7 "Google": Vertex {37.42202 , -122.08408} ,
8 }
map functions
1 m[key] = value
2 elem = m[key]
3 delete(m, key)
4 elem , ok = m[key]
Slide 78
Slide 78 text
Outline
1 How to Write Go Code
2 A Tour of Go
Hello World
Functions
Variables
Control Statements
Data Structures
Methods and Interfaces
Concurrency
3 Continue Reading
Revisit Pointer Cont.
You can pass pointer when
value is required
You can pass value when
pointer is required only as
method receiver (maybe a bug)
Slide 82
Slide 82 text
Methods Cont.
In fact, you can define a method
on any type you define in your
package, not just structs.
You cannot define a method on
a type from another package, or
on a basic type.
Interfaces
1 type SqrtError float64
2 func (err *SqrtError) Error () string {
3 return fmt.Sprintf("Sqrt:␣%v␣is␣nagative",
float64 (*err))
4 }
5 var err = SqrtError (3)
6 var x error = 1 // => type error
7 var y error = err // => type error
8 var z error = &err // => OK
Slide 87
Slide 87 text
Interfaces and Pointer
Methods defined on value is
considered defined on pointer
as well
Methods defined on pointer is
not defined on value
Slide 88
Slide 88 text
Interfaces and Pointer
1 type SqrtError float64
2 func (err SqrtError) Error () string {
3 return fmt.Sprintf("Sqrt:␣%v␣is␣nagative",
float64(err))
4 }
5 var err = SqrtError (3)
6 var x error = 1 // => type error
7 var y error = err // => OK
8 var z error = &err // => OK
Slide 89
Slide 89 text
Interfaces Union
1 type ReadWriter interface {
2 Reader
3 Writer
4 }
Slide 90
Slide 90 text
Embedding
1 type Job struct {
2 Command string
3 *log.Logger
4 }
Job has all methods defined on
log.Logger.
Slide 91
Slide 91 text
Embedding
Last part of the type name is
defined as implicit field name
1 func main() {
2 job := Job{Logger: log.New(os.Stderr , "Job:␣
", log.Ldate)}
3
4 fmt.Println(job)
5 }
Slide 92
Slide 92 text
Outline
1 How to Write Go Code
2 A Tour of Go
Hello World
Functions
Variables
Control Statements
Data Structures
Methods and Interfaces
Concurrency
3 Continue Reading
Slide 93
Slide 93 text
Goroutines
A goroutine is a lightweight
thread
1 go f(x, y, z)
Slide 94
Slide 94 text
Channels
Channels are a typed conduit
through which you can send and
receive values with the channel
operator, <-.
1 ch <- v // send v to channel
2 v := <-ch // receive from ch , and assign to v
select
1 select {
2 case c <- x:
3 x, y = y, x+y
4 case <-quit:
5 fmt.Println("quit")
6 return
7 }
Slide 101
Slide 101 text
non-blocking select
1 select {
2 case c <- x:
3 x, y = y, x+y
4 case <-quit:
5 fmt.Println("quit")
6 return
7 default:
8 time.Sleep (5e7)
9 }
Slide 102
Slide 102 text
Outline
1 How to Write Go Code
2 A Tour of Go
Hello World
Functions
Variables
Control Statements
Data Structures
Methods and Interfaces
Concurrency
3 Continue Reading
Slide 103
Slide 103 text
Continue Reading
Effective Go
Defer, Panic, and Recover
(similar to exception)
Concurrency Patterns
Packages Reference