A Tour of Go

A Tour of Go

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

17bca47a4961a24f82ef972aa9e1c986?s=128

Ian Yang

March 27, 2013
Tweet

Transcript

  1. 2.

    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. 3.

    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. 6.

    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. 9.

    Go Package All go files in a directory Do not

    find files recursively All files declare the same package
  5. 12.

    Package Search Search by import path Import path is relative

    directory path Search paths in GOPATH one by one
  6. 13.

    Package Search Search by import path Import path is relative

    directory path Search paths in GOPATH one by one pkg first, then src
  7. 20.

    Toolkit go build compile package go install compile and install

    go test run tests in *_test.go go get install remote packages
  8. 21.

    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. 22.

    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. 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
  11. 25.

    Hello World 1 package main 2 3 import "fmt" 4

    5 func main() { 6 fmt.Println("Hello ,␣World") 7 }
  12. 26.

    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. 27.

    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. 28.

    User will be confused. hello/main.go 1 package main 2 import

    "foo" 3 func main() { 4 bar.Greeting () 5 }
  15. 29.

    import 1 import "fmt" 2 import m "math" 3 4

    func main() { 5 fmt.Println(m.Pi) 6 }
  16. 30.

    in group 1 import ( 2 "fmt" 3 "math" 4

    ) 5 import ( 6 fmt "fmt" 7 m "math" 8 )
  17. 31.

    Exported names a name is exported if it begins with

    a capital letter. global var, const, type and func
  18. 33.

    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. 34.
  20. 35.

    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 }
  21. 36.

    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 }
  22. 37.

    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 }
  23. 38.

    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 }
  24. 39.

    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 }
  25. 40.

    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
  26. 45.

    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 }
  27. 46.

    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 }
  28. 47.

    Variables Scope block scope (except if) parameters and named results

    are in the scope of function block var, := hide the variable in parent scope
  29. 48.
  30. 49.

    Primitive Types Cont. byte alias of uint8 rune Unicode code,

    alias of int32 float32 float64 complex64 complex128
  31. 50.

    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 }
  32. 51.

    First class func 1 add = func(x, y int) int

    { 2 return x + y 3 } 4 fmt.Println(add(10, 20)) // => 30
  33. 52.

    Closure 1 func adder () func(int) int { 2 sum

    := 0 3 return func(int x) int { 4 sum += x 5 return sum 6 } 7 }
  34. 53.

    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
  35. 54.

    for no ( ) { } are required 1 sum

    := 0 2 for i := 1; i <= 10; i++ { 3 sum += i 4 }
  36. 55.

    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 }
  37. 56.

    for is while 1 sum , i := 0, 1

    2 for i <= 10 { 3 sum += i 4 }
  38. 58.

    if no ( ) { } are required 1 func

    abs(x int) int { 2 if x < 0 { 3 return -x 4 } 5 return x 6 }
  39. 59.

    if initializer 1 if name , err := m["name"]; ok

    { 2 fmt.Println(name) 3 } Variable declared in initializer is visible in all branches
  40. 60.

    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 }
  41. 61.

    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
  42. 62.

    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}
  43. 63.

    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 }
  44. 64.

    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 }
  45. 66.

    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 }
  46. 67.

    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]
  47. 68.

    Making slice 1 // make ([]T, lenth , capability) 2

    p := make ([]int , 0, 10) 3 cap(p) // => 10 4 len(p) // => 0
  48. 69.

    Slicing beyond len 1 p := make ([]int , 5,

    10) 2 p = p[3,8] // len(p)=5,cap(p)=7
  49. 71.

    append 1 func append(slice []Type , elems ... Type) []

    Type Slice the slice if capability is enough, otherwise allocate a new array.
  50. 72.

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

    slice = append(slice , anotherSlice ...)
  51. 73.

    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 }
  52. 74.

    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 }
  53. 75.

    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 }
  54. 76.

    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 }
  55. 77.

    map functions 1 m[key] = value 2 elem = m[key]

    3 delete(m, key) 4 elem , ok = m[key]
  56. 78.

    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
  57. 79.

    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 }
  58. 80.

    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 }
  59. 81.

    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)
  60. 82.

    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.
  61. 83.

    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)
  62. 84.

    Interfaces An interface type is defined by a set of

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

    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
  64. 87.

    Interfaces and Pointer Methods defined on value is considered defined

    on pointer as well Methods defined on pointer is not defined on value
  65. 88.

    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
  66. 90.

    Embedding 1 type Job struct { 2 Command string 3

    *log.Logger 4 } Job has all methods defined on log.Logger.
  67. 91.

    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 }
  68. 92.

    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
  69. 94.

    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
  70. 96.

    Channels Blocking sender is blocked until data is read by

    receiver receiver is blocked until data is placed by sender
  71. 97.

    Buffered Channels 1 ch := make(chan int , 10) 2

    queue = make(chan *Request , 100)
  72. 98.

    Buffered Channels Blocking sender is blocked when buffer is full

    receiver is blocked when buffer is empty
  73. 99.

    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 }
  74. 100.

    select 1 select { 2 case c <- x: 3

    x, y = y, x+y 4 case <-quit: 5 fmt.Println("quit") 6 return 7 }
  75. 101.

    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 }
  76. 102.

    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
  77. 103.

    Continue Reading Effective Go Defer, Panic, and Recover (similar to

    exception) Concurrency Patterns Packages Reference