$30 off During Our Annual Pro Sale. View Details »

Introduction to Go

Introduction to Go

An introduction to Go focused on teaching Bootcamp students learning Ruby the basics along with advantages and disadvantages.

Terrence Ryan

March 19, 2015
Tweet

More Decks by Terrence Ryan

Other Decks in Technology

Transcript

  1. @tpryan What is Go How to Write Go Why use

    Go (and why not) 1 2 3 Agenda
  2. @tpryan • Developed at Google • Open Source • Compiled

    What is Go? Go is a programming language
  3. @tpryan • Compiled • Garbage collected • Strongly typed •

    Statically typed • C syntax • Simple • Built to use multiple processors • Tools design for remote packages • Testing built in Language focused on Software engineering What is Go? Go features
  4. @tpryan 02_hellowworld/main.go package main import "fmt" func main() { var

    s string = "Hello World" fmt.Printf("%s\n", s) } Hello World How to Write Go
  5. Twitter: @tpryan Section Slide Template Option 2 Put your subtitle

    here. Feel free to pick from the handful of pretty Google colors available to you. Make the subtitle something clever. People will think it’s neat. Variables
  6. @tpryan Type inference var s string = "Hello World" s

    := "Hello World" Hello World How to Write Go
  7. @tpryan main.go package main import "fmt" func main() { s

    := "Hello World" fmt.Printf("%s\n", s) } Hello World How to Write Go
  8. @tpryan • bool • string • int int8 int16 int32

    int64 • uint uint8 uint16 uint32 uinint 64 uintptr • byte (uint8) • rune (int32) • float32 float 64 • complex64 complex128 What is Go? Go variables
  9. @tpryan • Array - finite, ordered collection of elements ◦

    users := [4]string What is Go? Go arrays vs slices 4 ? • Slice - points to an array, allows for more dynamic operations ◦ users :=[]strings
  10. @tpryan Slice Literal g := []string{"你好世界", "Hello wereld", "Hello world",

    "Bonjour monde", "Hallo Welt", "γειά σου κόσμος", "Ciao mondo", "こんにちは世界", "여보세요 세계", "Olá mundo", "Здравствулте мир", "Hola mundo"} Hello World How to Write Go
  11. @tpryan 03_helloworld/main.go package main import ( "fmt" "math/rand" "time" )

    func main() { g := []string{"你好世界", … } rand.Seed(time.Now().Unix()) l := len(g) i := rand.Intn(l - 1) fmt.Printf("%s\n", greetings[i]) } Hello World How to Write Go
  12. Twitter: @tpryan Section Slide Template Option 2 Put your subtitle

    here. Feel free to pick from the handful of pretty Google colors available to you. Make the subtitle something clever. People will think it’s neat. Input
  13. @tpryan 04_helloworld/main.go package main import ( "flag" "fmt" "log" "os"

    "strconv" ) func main() { i := flag.Int("lang", 0, " a number between 0 and 11") flag.Parse() a := []string{"你好世界", … } fmt.Printf("%s\n", a[i]) } Hello World How to Write Go
  14. Twitter: @tpryan Section Slide Template Option 2 Put your subtitle

    here. Feel free to pick from the handful of pretty Google colors available to you. Make the subtitle something clever. People will think it’s neat. Error Handling Part 1
  15. @tpryan Error Handling if *i >= len(g) { log.Fatalf("%d is

    not valid, please choose between 0 - %d", *i, len(a)) } Errors How to Write Go
  16. Twitter: @tpryan Section Slide Template Option 2 Put your subtitle

    here. Feel free to pick from the handful of pretty Google colors available to you. Make the subtitle something clever. People will think it’s neat. Finishing up the Program
  17. @tpryan Map Literal greetings := map[string]string{ "Chinese": "你好世界", "Dutch": "Hello

    wereld", "English": "Hello world", "French": "Bonjour monde", "German": "Hallo Welt", "Greek": "γειά σου κόσμος", "Italian": "Ciao mondo", "Japanese": "こんにちは世界", "Korean": "여보세요 세계", "Portuguese": "Olá mundo", "Russian": "Здравствулте мир", "Spanish": "Hola mundo", } Hello World How to Write Go
  18. @tpryan main.go func main() { l := flag.String("lang", "English", "a

    language in which to get greeting.") flag.Parse() g := map[string]string{"Chinese":"你好世界", … } if r, ok := g[*l]; ok { fmt.Printf("%s\n", r) } else { log.Fatal("The language you selected is not valid.") } } Hello World How to Write Go
  19. @tpryan main.rb greet_list = { 'Chinese' => "你好世界", … }

    lang = ARGV[0] lang = "English" if lang == nil response = greet_list[lang] if response == nil puts "The language you selected is not valid." else puts response end Hello World How to Write Go
  20. @tpryan main.go func main() { lang := flag.String("lang", "English", "a

    language in which to get greeting.") flag.Parse() greet_list := map[string]string{"Chinese":"你好世界", … } if result, ok := greet_list[*lang]; ok { fmt.Printf("%s\n", result) } else { log.Fatal("The language you selected is not valid.") } } Hello World How to Write Go
  21. @tpryan Variable names in Go should be short rather than

    long. This is especially true for local variables with limited scope. Prefer c to lineCount. Prefer i to sliceIndex. https://github.com/golang/go/wiki/CodeReviewComments#variable-names
  22. @tpryan "5-week-old Golden Retriever puppy" by Keagiles - Own work.

    Licensed under CC BY-SA 3.0 via Wikimedia Commons - http: //commons.wikimedia.org/wiki/File:5-week-old_Golden_Retriever_puppy.jpg#/media/File:5-week-old_Golden_Retriever_puppy.jpg Go - d Ruby - dog Java - GoldenRetrieverWithASadFace
  23. @tpryan main.go func main() { l := flag.String("lang", "English", "a

    language in which to get greeting.") flag.Parse() g := map[string]string{"Chinese":"你好世界", … } if r, ok := g[*l]; ok { fmt.Printf("%s\n", r) } else { log.Fatal("The language you selected is not valid.") } } Hello World How to Write Go
  24. @tpryan main.go if r, ok := g[*l]; ok { fmt.Printf("%s\n",

    r) } else { log.Fatal("The language you selected is not valid.") } Hello World How to Write Go
  25. @tpryan main.go r, ok := g[*l] if ok { fmt.Printf("%s\n",

    r) } else { log.Fatal("The language you selected is not valid.") } Hello World How to Write Go
  26. @tpryan main.go result, keyexists? := greeting[*language] if keyexists? { fmt.Printf("%s\n",

    result) } else { log.Fatal("The language you selected is not valid.") } Hello World How to Write Go
  27. @tpryan main.go if result, keyexists? := greeting[*language]; keyexists? { fmt.Printf("%s\n",

    result) } else { log.Fatal("The language you selected is not valid.") } Hello World How to Write Go
  28. @tpryan main.go if r, ok := g[*l]; ok { fmt.Printf("%s\n",

    r) } else { log.Fatal("The language you selected is not valid.") } Hello World How to Write Go
  29. @tpryan main.go func main() { l := flag.String("lang", "English", "a

    language in which to get greeting.") flag.Parse() g := map[string]string{"Chinese":"你好世界", … } if r, ok := g[*l]; ok { fmt.Printf("%s\n", r) } else { log.Fatal("The language you selected is not valid.") } } Hello World How to Write Go
  30. Twitter: @tpryan Section Slide Template Option 2 Put your subtitle

    here. Feel free to pick from the handful of pretty Google colors available to you. Make the subtitle something clever. People will think it’s neat. Tooling Part 1
  31. @tpryan • All Go projects happen in workspaces • All

    Go workspaces have 3 parts: ◦ src ◦ bin ◦ pkg • Most everything happens in src ◦ github.com/username/project • Set folder that contains src, bin, pkg to GOPATH ◦ export GOPATH=$HOME/go What is Go? Go Path
  32. Twitter: @tpryan Section Slide Template Option 2 Put your subtitle

    here. Feel free to pick from the handful of pretty Google colors available to you. Make the subtitle something clever. People will think it’s neat. Package
  33. @tpryan helloworld.go package helloworld import "errors" var greetings = map[string]string{"Chinese":

    "你好世界", … } func Greet(language string) (string, error) { if r, ok := greetings[language]; ok { return r, nil } else { return "", errors.New("The language you selected is not valid.") } } Hello World How to Write Go
  34. Twitter: @tpryan Section Slide Template Option 2 Put your subtitle

    here. Feel free to pick from the handful of pretty Google colors available to you. Make the subtitle something clever. People will think it’s neat. Error Handling Part 2
  35. @tpryan Error Handling func Greet(language string) (string, error) { if

    r, ok := greetings[language]; ok { return r, nil } else { return "", errors.New(errorNotFound) } } Hello World How to Write Go
  36. @tpryan error handling func main() { l := flag.String("lang", "English",

    "a language in which to get greeting.") flag.Parse() greet, err := helloworld.Greet(*l) if err != nil { log.Fatal(err) } fmt.Printf("%s\n", greet) } Hello World How to Write Go
  37. @tpryan main.go cont func main() { l := flag.String("lang", "English",

    "a language in which to get greeting.") flag.Parse() greet, err := helloworld.Greet(*l) if err != nil { if strings.Contains(err.Error(), helloworld.ErrorNotFound) { listLanguages() } else { log.Fatal(err) } } fmt.Printf("%s\n", greet) } Hello World How to Write Go
  38. Twitter: @tpryan Section Slide Template Option 2 Put your subtitle

    here. Feel free to pick from the handful of pretty Google colors available to you. Make the subtitle something clever. People will think it’s neat. What’s Next
  39. @tpryan helloworld.go package helloworld import "errors" var greetings = map[string]string{"Chinese":

    "你好世界", … } func Greet(language string) (string, error) func Langauges() []string Hello World How to Write Go
  40. @tpryan main.go package main import ( "encoding/json" "errors" "fmt" "log"

    "net/http" "github.com/tpryan/gosamples/helloworld" ) func main() { http.HandleFunc("/get", HandleGet) http.HandleFunc("/list", HandleList) log.Print(http.ListenAndServe(":8080", nil)) } Hello World How to Write Go
  41. @tpryan main.go cont func HandleList(w http.ResponseWriter, r *http.Request) { list

    := helloworld.Langauges() js, err := json.Marshal(list) if err != nil { handleError(w, err) return } sendJSON(w, string(js)) } Hello World How to Write Go
  42. @tpryan main.go cont func handleError(w http.ResponseWriter, err error) { http.Error(w,

    err.Error(), http.StatusInternalServerError) log.Print(err) } func sendJSON(w http.ResponseWriter, content string) { w.Header().Set("Content-Type", "application/json") fmt.Fprint(w, content) } Hello World How to Write Go
  43. @tpryan main.go cont func HandleGet(w http.ResponseWriter, r *http.Request) { lang

    := r.FormValue("language") greet, err := helloworld.Greet(lang) if err != nil { handleError(w, err) return } sendJSON(w, greet) } Hello World How to Write Go
  44. Twitter: @tpryan Section Slide Template Option 2 Put your subtitle

    here. Feel free to pick from the handful of pretty Google colors available to you. Make the subtitle something clever. People will think it’s neat. Concurrency
  45. Twitter: @tpryan Section Slide Template Option 2 Put your subtitle

    here. Feel free to pick from the handful of pretty Google colors available to you. Make the subtitle something clever. People will think it’s neat. Tooling Part 2
  46. @tpryan export.go textout/scripts/test.sh 1 Executing ruby test 0.355 Executing php

    test 0.371 Executing go test 0.085 Publish Static Data How to Write Go
  47. @tpryan export.go textout/scripts/test.sh 10 Executing ruby test 0.654 Executing php

    test 0.803 Executing go test 0.290 Publish Static Data How to Write Go
  48. @tpryan export.go textout/scripts/test.sh 100 Executing ruby test 5.659 Executing php

    test 5.655 Executing go test 2.866 Publish Static Data How to Write Go
  49. @tpryan export.go textout/scripts/test.sh 1000 Executing ruby test 55.812 Executing php

    test 63.783 Executing go test 72.416 Publish Static Data How to Write Go
  50. @tpryan Task 2 Get Airport Latitude and Longitude Data Compute

    Distance between 2 Cities using Haversine Formula Write to Disk
  51. @tpryan calc.rb def deg2rad(deg) deg * Math::PI / 180 end

    def getDistance(lat1, lon1, lat2, lon2) earth_radius = 3963 # in miles dLat = deg2rad(lat2 - lat1) dLon = deg2rad(lon2 - lon1) a = Math.sin(dLat/2)*Math.sin(dLat/2) + Math.cos(deg2rad(lat1))*Math.cos(deg2rad(lat2))*Math.sin(dLon/2)*Math.sin(dLon/2) c = 2 * Math.asin(Math.sqrt(a)) d = earth_radius * c end Haversine formula Why use Go (and why not)
  52. @tpryan calc.go calc/scripts/test.sh 1 Executing ruby test 0.084 Executing php

    test 0.123 Executing go test 0.009 Number Crunching How to Write Go
  53. @tpryan calc.go calc/scripts/test.sh 1000 Executing ruby test 0.105 Executing php

    test 0.128 Executing go test 0.017 Number Crunching How to Write Go
  54. @tpryan calc.go calc/scripts/test.sh 1000000 Executing ruby test 40.081 Executing php

    test 65.140 Executing go test 12.170 Number Crunching How to Write Go
  55. @tpryan Task 3 Get password from Randomly Generated list Test

    if password conforms to rules Include a dictionary check Pa$$w0rdCh3ck
  56. @tpryan calc.rb FAIL_EMPTY if candidate.length == 0 FAIL_MIN if candidate.length

    < MIN_LENGTH FAIL_MAX if candidate.length > MAX_LENGTH FAIL_UPPER unless candidate =~ /[A-Z]/ FAIL_LOWER unless candidate =~ /[a-z]/ FAIL_NUMBER unless candidate =~ /[0-9]/ FAIL_SPECIAL unless candidate =~ /[#{SPECIAL}]/ word = hashMatch(candidate) FAIL_DICTIONARY if word.length > 0 SUCCESS Password Psuedo Code Why use Go (and why not)
  57. @tpryan Method 1 Pa$$w0rdCh3ck "AALII", "AALIIS", "AALS", "AARDVARK", "AARDVARKS", "AARDWOLF",

    "AARDWOLVES", "AARGH", "AARRGH", "AARRGHH", "AAS", "AASVOGEL", "AASVOGELS", "AB", Bruteforce
  58. @tpryan password.go password/scripts/test.sh 1 bruteforce Executing ruby test 1.678 Executing

    php test 0.409 Executing go test 0.117 Password Testing How to Write Go
  59. @tpryan password.go password/scripts/test.sh 100 bruteforce Executing ruby test 4.157 Executing

    php test 7.024 Executing go test 0.446 Password Testing How to Write Go
  60. @tpryan password.go password/scripts/test.sh 1000 bruteforce Executing ruby test 28.383 Executing

    php test 71.505 Executing go test 4.069 Password Testing How to Write Go
  61. @tpryan Method 2 Pa$$w0rdCh3ck "AALII", "AALIIS", "AALS", "AARDVARK", "AARDVARKS", "AARDWOLF",

    "AARDWOLVES", "AARGH", "AARRGH", "AARRGHH", "AAS", "AASVOGEL", "AASVOGELS", "AB", Hash "Pa$$", "a$$w", "$$w0", "$w0r", "w0rd", "0rdC", "rdCh", "dCh3", "Ch3c", "h3ck", "Pa$$w", "a$$w0", "$$w0r", "$w0rd",
  62. @tpryan password.go password/scripts/test.sh 1 hash Executing ruby test 1.830 Executing

    php test 0.318 Executing go test 0.097 Password Testing How to Write Go
  63. @tpryan password.go password/scripts/test.sh 100 hash Executing ruby test 1.848 Executing

    php test 0.318 Executing go test 0.095 Password Testing How to Write Go
  64. @tpryan password.go password/scripts/test.sh 1000 hash Executing ruby test 1.888 Executing

    php test 0.328 Executing go test 0.107 Password Testing How to Write Go
  65. @tpryan Consider using Go when you run into one of

    these problems – That guy from Google
  66. Twitter: @tpryan Thank you! Thank you! terrenceryan.com twitter.com/tpryan http://bit.ly/tpryan-go All

    Code in presentation is licensed under Apache: https://github.com/tpryan/SharedCode/ This work is licensed under a Creative Commons Attribution 2.0 Generic License.