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. A Tour of Go
    Who? Ian Yang
    From? Intridea Inc.
    When? March 27, 2013

    View Slide

  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

    View Slide

  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

    View Slide

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

    View Slide

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

    View Slide

  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

    View Slide

  7. Go Package
    All go files in a directory

    View Slide

  8. Go Package
    All go files in a directory
    Do not find files recursively

    View Slide

  9. Go Package
    All go files in a directory
    Do not find files recursively
    All files declare the same
    package

    View Slide

  10. Package Search
    Search by import path

    View Slide

  11. Package Search
    Search by import path
    Import path is relative directory
    path

    View Slide

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

    View Slide

  13. Package Search
    Search by import path
    Import path is relative directory
    path
    Search paths in GOPATH one by
    one
    pkg first, then src

    View Slide

  14. Executable
    A package that declares package
    main

    View Slide

  15. Executable
    A package that declares package
    main
    Installed into bin

    View Slide

  16. Executable
    A package that declares package
    main
    Installed into bin
    Run func main

    View Slide

  17. Toolkit
    go build compile package

    View Slide

  18. Toolkit
    go build compile package
    go install compile and install

    View Slide

  19. Toolkit
    go build compile package
    go install compile and install
    go test run tests in *_test.go

    View Slide

  20. Toolkit
    go build compile package
    go install compile and install
    go test run tests in *_test.go
    go get install remote packages

    View Slide

  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

    View Slide

  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

    View Slide

  23. A Tour of Go
    Let's rock with the online tour
    tour.golang.org

    View Slide

  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

    View Slide

  25. Hello World
    1
    package main
    2
    3
    import "fmt"
    4
    5
    func main() {
    6
    fmt.Println("Hello ,␣World")
    7
    }

    View Slide

  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

    View Slide

  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
    }

    View Slide

  28. User will be confused.
    hello/main.go
    1
    package main
    2
    import "foo"
    3
    func main() {
    4
    bar.Greeting ()
    5
    }

    View Slide

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

    View Slide

  30. in group
    1
    import (
    2
    "fmt"
    3
    "math"
    4
    )
    5
    import (
    6
    fmt "fmt"
    7
    m "math"
    8
    )

    View Slide

  31. Exported names
    a name is exported if it begins
    with a capital letter.
    global var, const, type and func

    View Slide

  32. General Declaration
    Rules
    type after variable
    type is optional if it can be
    deduced

    View Slide

  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

    View Slide

  34. func
    1 func sum(x int , y int) int {
    2 return x + y;
    3 }

    View Slide

  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 }

    View Slide

  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 }

    View Slide

  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 }

    View Slide

  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 }

    View Slide

  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 }

    View Slide

  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

    View Slide

  41. Variables
    The var statement declares a
    list of variables.
    1 var a, b, c int

    View Slide

  42. Variables Cont.
    Cross multiple lines
    1 var (
    2 a int
    3 b string
    4 )

    View Slide

  43. Variables initializer
    1 var x, y, z = true , "foo", 3.14

    View Slide

  44. Variables initializer
    Cont.
    Cross multiple lines
    1 var (
    2 a int = 10
    3 b = "foo"
    4 )

    View Slide

  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 }

    View Slide

  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 }

    View Slide

  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

    View Slide

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

    View Slide

  49. Primitive Types Cont.
    byte alias of uint8
    rune Unicode code, alias of int32
    float32 float64
    complex64 complex128

    View Slide

  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 }

    View Slide

  51. First class func
    1 add = func(x, y int) int {
    2 return x + y
    3 }
    4 fmt.Println(add(10, 20)) // => 30

    View Slide

  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 }

    View Slide

  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

    View Slide

  54. for
    no ( )
    { } are required
    1 sum := 0
    2 for i := 1; i <= 10; i++ {
    3 sum += i
    4 }

    View Slide

  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 }

    View Slide

  56. for is while
    1 sum , i := 0, 1
    2 for i <= 10 {
    3 sum += i
    4 }

    View Slide

  57. forever
    1 for {
    2 serve(<-req)
    3 }

    View Slide

  58. if
    no ( )
    { } are required
    1 func abs(x int) int {
    2 if x < 0 {
    3 return -x
    4 }
    5 return x
    6 }

    View Slide

  59. if initializer
    1 if name , err := m["name"]; ok {
    2 fmt.Println(name)
    3 }
    Variable declared in initializer is
    visible in all branches

    View Slide

  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 }

    View Slide

  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

    View Slide

  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}

    View Slide

  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 }

    View Slide

  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 }

    View Slide

  65. new
    1 var p *T = new(T)
    2 p: = new(T)

    View Slide

  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 }

    View Slide

  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]

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  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 }

    View Slide

  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 }

    View Slide

  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 }

    View Slide

  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 }

    View Slide

  77. map functions
    1 m[key] = value
    2 elem = m[key]
    3 delete(m, key)
    4 elem , ok = m[key]

    View Slide

  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

    View Slide

  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 }

    View Slide

  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 }

    View Slide

  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)

    View Slide

  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.

    View Slide

  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)

    View Slide

  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.

    View Slide

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

    View Slide

  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

    View Slide

  87. Interfaces and Pointer
    Methods defined on value is
    considered defined on pointer
    as well
    Methods defined on pointer is
    not defined on value

    View Slide

  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

    View Slide

  89. Interfaces Union
    1 type ReadWriter interface {
    2 Reader
    3 Writer
    4 }

    View Slide

  90. Embedding
    1 type Job struct {
    2 Command string
    3 *log.Logger
    4 }
    Job has all methods defined on
    log.Logger.

    View Slide

  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 }

    View Slide

  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

    View Slide

  93. Goroutines
    A goroutine is a lightweight
    thread
    1 go f(x, y, z)

    View Slide

  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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  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 }

    View Slide

  100. select
    1 select {
    2 case c <- x:
    3 x, y = y, x+y
    4 case <-quit:
    5 fmt.Println("quit")
    6 return
    7 }

    View Slide

  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 }

    View Slide

  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

    View Slide

  103. Continue Reading
    Effective Go
    Defer, Panic, and Recover
    (similar to exception)
    Concurrency Patterns
    Packages Reference

    View Slide