Upgrade to Pro — share decks privately, control downloads, hide ads and more …

A Tour of Go

A Tour of Go

Introduction to Go programming language based on tour.golang.org

Ian Yang

March 27, 2013
Tweet

More Decks by Ian Yang

Other Decks in Programming

Transcript

  1. 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
  2. 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
  3. Directory Structure 1 go 2 |- bin 3 | `-

    hello 4 |- src 5 | `- github.com/doitian/studygo 6 `- pkg 7 `- linux_amd64/github.com/doitian/ studygo
  4. Go Package All go files in a directory Do not

    find files recursively All files declare the same package
  5. Package Search Search by import path Import path is relative

    directory path Search paths in GOPATH one by one
  6. Package Search Search by import path Import path is relative

    directory path Search paths in GOPATH one by one pkg first, then src
  7. Toolkit go build compile package go install compile and install

    go test run tests in *_test.go go get install remote packages
  8. 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
  9. 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
  10. 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
  11. Hello World 1 package main 2 3 import "fmt" 4

    5 func main() { 6 fmt.Println("Hello ,␣World") 7 }
  12. 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
  13. 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 }
  14. User will be confused. hello/main.go 1 package main 2 import

    "foo" 3 func main() { 4 bar.Greeting () 5 }
  15. import 1 import "fmt" 2 import m "math" 3 4

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

    ) 5 import ( 6 fmt "fmt" 7 m "math" 8 )
  17. Exported names a name is exported if it begins with

    a capital letter. global var, const, type and func
  18. 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
  19. 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 }
  20. 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 }
  21. 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 }
  22. 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 }
  23. 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 }
  24. 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
  25. 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 }
  26. 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 }
  27. Variables Scope block scope (except if) parameters and named results

    are in the scope of function block var, := hide the variable in parent scope
  28. Primitive Types Cont. byte alias of uint8 rune Unicode code,

    alias of int32 float32 float64 complex64 complex128
  29. 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 }
  30. First class func 1 add = func(x, y int) int

    { 2 return x + y 3 } 4 fmt.Println(add(10, 20)) // => 30
  31. Closure 1 func adder () func(int) int { 2 sum

    := 0 3 return func(int x) int { 4 sum += x 5 return sum 6 } 7 }
  32. 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
  33. for no ( ) { } are required 1 sum

    := 0 2 for i := 1; i <= 10; i++ { 3 sum += i 4 }
  34. 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 }
  35. for is while 1 sum , i := 0, 1

    2 for i <= 10 { 3 sum += i 4 }
  36. if no ( ) { } are required 1 func

    abs(x int) int { 2 if x < 0 { 3 return -x 4 } 5 return x 6 }
  37. if initializer 1 if name , err := m["name"]; ok

    { 2 fmt.Println(name) 3 } Variable declared in initializer is visible in all branches
  38. 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 }
  39. 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
  40. 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}
  41. 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 }
  42. 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 }
  43. 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 }
  44. 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]
  45. Making slice 1 // make ([]T, lenth , capability) 2

    p := make ([]int , 0, 10) 3 cap(p) // => 10 4 len(p) // => 0
  46. Slicing beyond len 1 p := make ([]int , 5,

    10) 2 p = p[3,8] // len(p)=5,cap(p)=7
  47. append 1 func append(slice []Type , elems ... Type) []

    Type Slice the slice if capability is enough, otherwise allocate a new array.
  48. append 1 slice = append(slice , elem1 , elem2) 2

    slice = append(slice , anotherSlice ...)
  49. 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 }
  50. 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 }
  51. 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 }
  52. 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 }
  53. map functions 1 m[key] = value 2 elem = m[key]

    3 delete(m, key) 4 elem , ok = m[key]
  54. 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
  55. 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 }
  56. 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 }
  57. 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)
  58. 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.
  59. 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)
  60. Interfaces An interface type is defined by a set of

    methods. A value of interface type can hold any value that implements those methods.
  61. 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
  62. Interfaces and Pointer Methods defined on value is considered defined

    on pointer as well Methods defined on pointer is not defined on value
  63. 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
  64. Embedding 1 type Job struct { 2 Command string 3

    *log.Logger 4 } Job has all methods defined on log.Logger.
  65. 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 }
  66. 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
  67. 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
  68. Channels Blocking sender is blocked until data is read by

    receiver receiver is blocked until data is placed by sender
  69. Buffered Channels 1 ch := make(chan int , 10) 2

    queue = make(chan *Request , 100)
  70. Buffered Channels Blocking sender is blocked when buffer is full

    receiver is blocked when buffer is empty
  71. 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 }
  72. select 1 select { 2 case c <- x: 3

    x, y = y, x+y 4 case <-quit: 5 fmt.Println("quit") 6 return 7 }
  73. 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 }
  74. 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
  75. Continue Reading Effective Go Defer, Panic, and Recover (similar to

    exception) Concurrency Patterns Packages Reference