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

Go 102: A Workshop

timblair
November 26, 2015

Go 102: A Workshop

This is the slide deck to accompany the workshop I gave on 2015-11-26. The content covers:

* A quick introduction: built-in types, variable declaration, function and custom types.
* Object oriented development: methods, interfaces, embedding and composition.
* Concurrency: goroutines and channels.

Each section ended with a hands-on exercise to apply the information from that section. The detailed material from the workshop (including the exercises) is available at: https://github.com/timblair/go-102

timblair

November 26, 2015
Tweet

More Decks by timblair

Other Decks in Programming

Transcript

  1. The Language Designed for concurrent systems programming, Strongly and statically

    typed, Compiled, Garbage collected, Object oriented (ish), Small, opinionated, and done.
  2. Basic Types b1 := true // type is bool b2

    := false n1 := 123 // int n2 := 123.456 // float32/64 n3 := 1e10 // float32/64 n4 := uint8(123) // uint n5 := float32(123) // float32 s1 := `Raw string literal` s2 := "Interpreted string literal"
  3. Variable Declaration var x T // Variable x of type

    T with a zero value var x T = v // Variable x of type T with value v var x = v // Variable x with value v, implicit typing x := v // Short variable declaration (type inferred) x, y := v1, v2 // Double declaration (similar with var) make(T) // make takes a type T, which must be a slice, // map or channel type, optionally followed by // a type-specific list of expressions
  4. Zero Values 0 // numeric false // boolean "" //

    string nil // pointer, channel, func, // interface, map, or slice
  5. Structs type rectangle struct { width int height int }

    r1 := rectangle{1, 2} // New rectangle with w + h r1.width = 3 // Set width to a new value fmt.Printf("Width = %d; Height = %d\n", r1.width, r1.height) var r2 rectangle // w=0, h=0 (int zero values) r4 := rectangle{} // w=0, h=0 r3 := rectangle{height: 1} // w=0, h=1
  6. Functions func f1() {} // Simple function definition func f2(s

    string, i int) {} // Function that accepts two args func f3(s1, s2 string) {} // Two args of the same type func f4(s ...string) {} // Variadic function func f5() int { // Return type declaration return 42 } func f6() (int, string) { // Multiple return values return 42, "foo" }
  7. Exercise Declare a struct type to maintain information about a

    person. Declare a function that creates new values of your type. Call this function from main and display the value.
  8. What have we covered? Built-in Types & value declaration All

    types have a zero value structs as collections of named fields functions
  9. Object Orientation OOP is about objects. An object is a

    data structure that has both state and behaviour
  10. Methods type rectangle struct { width int height int }

    func area(r rectangle) int { return r.width * r.height } func main() { r := rectangle{3, 4} fmt.Println(area(r)) // area 12 }
  11. Methods type rectangle struct { width int height int }

    func (r rectangle) area() int { return r.width * r.height } func main() { r := rectangle{3, 4} fmt.Println(r.area()) // area 12 }
  12. Methods // function, called with area(r) func area(r rectangle) int

    { return r.width * r.height } // method, called with r.area() func (r rectangle) area() int { return r.width * r.height }
  13. Methods Declare a new struct type to hold information about

    a tennis player, including the number of matches played and the number won. Add a method to this type that calculates the win ratio for the player. Create a new player, and output the win ratio for them.
  14. Methods methods are functions that are bound to a receiver

    A receiver can be any named type Methods are effectively syntactic sugar
  15. Interfaces type hipster struct { } func (h hipster) speak()

    string { return "Amazeballs" } func (h hipster) trimBeard() { /* ... */ } type dog struct { } func (d dog) speak() string { return "Woof" } func (d dog) wagTail() { /* ... */ } type robot struct { } func (r robot) speak() string { return "Does not compute" } func (r robot) becomeSentient() { /* ... */ }
  16. Interfaces // We can treat a hipster as a speaker

    var s1 speaker s1 = hipster{} // We can also create a slice of different speakers speakers := []speaker{hipster{}, dog{}, robot{}} for _, s := range speakers { fmt.Printf("%T: %s\n", s, s.speak()) } // main.hipster: Amazeballs // main.dog: Woof // main.robot: Does not compute
  17. Interfaces type email struct { name string address string }

    func (e email) String() string { return fmt.Sprintf("\"%s\" <%s>", e.name, e.address) } e := email{"Tim Blair", "[email protected]"} fmt.Println(e) // "Tim Blair" <[email protected]>
  18. Interfaces Define an interface with a method Area(). Create types

    for Square, Rectangle and Circle, and ensure they satisfy your interface. Create a function that accepts a value of your interface type and outputs the area, and call this function for different shapes.
  19. Interfaces Interfaces are types that declare behaviour they provide polymorphism

    behaviour no `implements` keyword; satisfied implicitly
  20. Embedding type sphere struct { x, y, z, radius int

    } type cube struct { x, y, z, length int }
  21. Embedding type point struct { x, y, z int }

    type sphere struct { point point radius int } type cube struct { point point length int } var s sphere s.point.x = 5 s.point.y = 6 s.point.z = 7 s.radius = 3
  22. Embedding type point struct { x, y, z int }

    type sphere struct { point radius int } type cube struct { point length int } var s sphere s.x = 5 s.y = 6 s.z = 7 s.radius = 3
  23. Embedding s1 := sphere{point{1, 2, 3}, 5} s2 := sphere{

    point: point{ 1, 2, 3, }, radius: 5, // required trailing comma }
  24. Embedding type robot struct { } func (r robot) talk()

    { fmt.Println("Bzzzzzbt") } type robby struct { robot } robby := robby{} robby.talk() // Bzzzzzbt
  25. Embedding type robot struct { } func (r robot) talk()

    { fmt.Println("Bzzzzzbt") } type robby struct { robot } func (r robby) talk() { fmt.Println("Again?") } robby := robby{} robby.talk() // Again?
  26. Embedding type talker interface { talk() } type robot struct{}

    func (r robot) talk() { fmt.Println("Bzzzzzbt") } type robby struct { robot } func talk(t talker) { t.talk() } talk(robby{})
  27. Embedding Create a user type, and an admin type that

    embeds a user. Create a Notifier interface, and make your user type satisfy that interface. Write a function that accepts a value of the interface type, and ensure it works correctly when passed a value of your admin type.
  28. Embedding composition is supported through type embedding anonymous struct fields

    are said to be embedded Both inner types and methods are promoted Promoted methods can satisfy an interface
  29. Composition "Everyone knows composition is more powerful than inheritance, Go

    just makes this non optional." –– Dave Cheney: http://bit.ly/dctlg
  30. Composition type point struct { x, y int } type

    mover interface { moveTo(p point) } type firer interface { fire() }
  31. Composition type vehicle struct { point passengers int } func

    (v *vehicle) moveTo(p point) { v.point = p } type weapon struct { loaded bool } func (w *weapon) fire() { w.loaded = false }
  32. Composition type moverFirer interface { mover firer } func moveAndFire(mf

    moverFirer, p point) { mf.moveTo(p) mf.fire() }
  33. Composition func main() { t := &tank{ vehicle{point{5, 6}, 6},

    weapon{true}, } moveAndFire(t, point{10, 20}) fmt.Printf("Location: %v; Passengers: %d; Loaded: %t\n", t.point, t.passengers, t.loaded) // Location: {10 20}; Passengers: 6; Loaded: false }
  34. Composition Composition is a design pattern discrete behaviours are defined

    through interfaces they are implemented via methods in concrete types Simple behaviours are composed to give complexity
  35. goroutines func doWork(i int) { time.Sleep(time.Millisecond * 500) fmt.Println(i) }

    func main() { for i := 1; i <= 5; i++ { doWork(i) } }
  36. goroutines $ time go run g1.go 1 2 3 4

    5 go run g1.go ... 2.757 total
  37. goroutines func doWork(i int) { time.Sleep(time.Millisecond * 500) fmt.Println(i) }

    func main() { for i := 1; i <= 5; i++ { go doWork(i) // Concurrency! } }
  38. Goroutines import "sync" func main() { var wg sync.WaitGroup wg.Add(1)

    go func() { // Do work... wg.Done() }() wg.Wait() }
  39. GOroutines func main() { var wg sync.WaitGroup for i :=

    1; i <= 5; i++ { wg.Add(1) go func(x int) { defer wg.Done() doWork(x) }(i) } wg.Wait() }
  40. goroutines $ time go run g3.go 4 1 5 2

    3 go run g3.go ... 0.752 total
  41. Goroutines Create two anonymous functions: one that outputs integers from

    1 to 100; the other from 100 to 1. Start each function as a goroutine. Use a WaitGroup to ensure that main() doesn't exit until the goroutines are done.
  42. Goroutines A Goroutine is a function running independently Effectively Lightweight

    threads Multiplexed against one or more OS threads WaitGroups can be used to signal goroutine completion
  43. Channels "Do not communicate by sharing memory; instead, share memory

    by communicating." -- https://golang.org/doc/effective_go.html
  44. Channels ch := make(chan int) ch <- 42 // Send

    a value to the channel v := <-ch // Receive a value from ch
  45. Channels c1 := make(chan int) // Unbuffered c2 := make(chan

    int, 0) // Unbuffered c3 := make(chan int, 100) // Buffered
  46. Channels func search(q string, server string) string { /* ...

    */ } func parallelSearch(q string, servers []string) string { res := make(chan string, 3) for _, s := range servers { go func(x string) { res <- search(q, x) }(s) } return <-res } servers := []string{"s1", "s2", "s3"} fmt.Println(parallelSearch("foo", servers))
  47. Channels ch := make(chan int) close(ch) // Close the channel

    for writing v, ok := <-ch // Receive, testing for closure if !ok { fmt.Println("Channel closed!") }
  48. Channels ch := make(chan int) // Read from channel until

    it is closed for i := range ch { fmt.Println(i) }
  49. Channels var wg sync.WaitGroup func main() { court := make(chan

    struct{}) // An unbuffered channel. wg.Add(2) // Add two to the WG, one for each player. // Launch two players. go player("Serena", court) go player("Venus", court) court <- struct{}{} // Serve the "ball." wg.Wait() // Wait for the game to finish. }
  50. Channels func player(name string, court chan struct{}) { for {

    ball := <-court fmt.Println(name, "hit the ball") court <- ball // Hit the ball back. } }
  51. Channels func player(name string, court chan struct{}) { for {

    ball, ok := <-court if !ok { // If the channel was closed we won. fmt.Println(name, "won!") return } fmt.Println(name, "hit the ball") court <- ball // Hit the ball back. } }
  52. Channels func player(name string, court chan struct{}) { for {

    // Receive step excluded... if rand.Intn(10) == 0 { // Decide if we missed the ball. fmt.Println(name, "missed the ball") close(court) // Close the channel to signal we lost. return } fmt.Println(name, "hit the ball") court <- ball // Hit the ball back. } }
  53. Channels $ go run tennis.go Venus hit the ball Serena

    hit the ball Venus hit the ball Serena hit the ball Venus hit the ball Serena hit the ball Venus missed the ball Serena won!
  54. Channels Create a channel representing a track, and a function

    representing a runner. Pass a baton between runners over the channel, and end the race when the fourth runner receives the baton.
  55. Goroutines Channels are used to communicate between goroutines Avoids the

    need for locking around data structures Channels can be buffered or unbuffered Closing a channel can be used as a signalling mechanism