Slide 1

Slide 1 text

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

Slide 4

Slide 4 text

How to Write Go Code golang.org/doc/code.html

Slide 5

Slide 5 text

GOPATH 1 mkdir -p ~/go/src 2 export GOPATH =~/go

Slide 6

Slide 6 text

Directory Structure 1 go 2 |- bin 3 | `- hello 4 |- src 5 | `- github.com/doitian/studygo 6 `- pkg 7 `- linux_amd64/github.com/doitian/ studygo

Slide 7

Slide 7 text

Go Package All go files in a directory

Slide 8

Slide 8 text

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 }

Slide 29

Slide 29 text

import 1 import "fmt" 2 import m "math" 3 4 func main() { 5 fmt.Println(m.Pi) 6 }

Slide 30

Slide 30 text

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 }

Slide 38

Slide 38 text

Comma err pattern 1 import "os" 2 import "log" 3 4 func main() { 5 file , err := os.Open("file.go") 6 if err != nil { 7 log.Fatal(err) 8 } 9 }

Slide 39

Slide 39 text

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

Slide 48

Slide 48 text

Primitive Types bool string int int8 int16 int32 int64 uint uint8 uint16 uint32 uint64 uintptr

Slide 49

Slide 49 text

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 }

Slide 67

Slide 67 text

Slicing Slices 1 p := []int{2, 3, 5, 7, 11, 13} 2 p[1:4] // => [3,5,7] 3 p[1:] // => [3,5,7,11,13] 4 p[:4] // => [2,3,5,7]

Slide 68

Slide 68 text

Making slice 1 // make ([]T, lenth , capability) 2 p := make ([]int , 0, 10) 3 cap(p) // => 10 4 len(p) // => 0

Slide 69

Slide 69 text

Slicing beyond len 1 p := make ([]int , 5, 10) 2 p = p[3,8] // len(p)=5,cap(p)=7

Slide 70

Slide 70 text

1 p := make ([]int , 5, 10)

Slide 71

Slide 71 text

append 1 func append(slice []Type , elems ... Type) [] Type Slice the slice if capability is enough, otherwise allocate a new array.

Slide 72

Slide 72 text

append 1 slice = append(slice , elem1 , elem2) 2 slice = append(slice , anotherSlice ...)

Slide 73

Slide 73 text

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 }

Slide 76

Slide 76 text

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

Slide 77

Slide 77 text

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

Slide 79

Slide 79 text

Methods 1 type Vertex struct{ X, Y float64 } 2 func (v *Vertex) double () { 3 v.X, v.Y = v.X*2, v.Y*2 4 } 5 6 func main() { 7 v := &Vertex{1, 2} 8 v.double () // => &Vertex {2,4} 9 }

Slide 80

Slide 80 text

Revisit Pointer 1 type Vertex struct{ X, Y float64 } 2 func (v Vertex) double () { 3 v.X, v.Y = v.X*2, v.Y*2 4 } 5 6 func main() { 7 v := &Vertex{1, 2} 8 v.double () // => &Vertex {1,2} 9 }

Slide 81

Slide 81 text

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.

Slide 83

Slide 83 text

Methods Cont. 1 type SqrtError float64 2 3 func (err SqrtError) Error () string { 4 return fmt.Sprintf("Sqrt:␣%v␣is␣nagative", float64(err)) 5 } 6 7 var err = SqrtError (-64)

Slide 84

Slide 84 text

Interfaces An interface type is defined by a set of methods. A value of interface type can hold any value that implements those methods.

Slide 85

Slide 85 text

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

Slide 86

Slide 86 text

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

Slide 95

Slide 95 text

Making Channels 1 ch := make(chan int) 2 queue = make(chan *Request)

Slide 96

Slide 96 text

Channels Blocking sender is blocked until data is read by receiver receiver is blocked until data is placed by sender

Slide 97

Slide 97 text

Buffered Channels 1 ch := make(chan int , 10) 2 queue = make(chan *Request , 100)

Slide 98

Slide 98 text

Buffered Channels Blocking sender is blocked when buffer is full receiver is blocked when buffer is empty

Slide 99

Slide 99 text

1 func worker(a []int , ch chan int) { 2 result := sum(a) 3 ch <- result 4 } 5 6 func main() { 7 ch := make(chan int) 8 go worker ([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, ch) 9 10 fmt.Println(<-ch) // => 3 11 }

Slide 100

Slide 100 text

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