SlideShare a Scribd company logo
Go
Lightning talk 2017-11-23
● Created by Google for Google scale problems
● First class concurrency support
● Easy to learn, easy to use
● Good performance by default
● C++ too hard, Python too slow, few enjoyed Java
Background
● Strong, static typed language
● Garbage Collected
● Compiles to a binary
● Easy cross compilation
What is it?
Saker Go inte har:
● Klasser
● Konstruktorer/destruktorer
● Ineheritance
● Exceptions
● Annotations
● Generics
● (100% bakåtkompatibelt så länge 1.X)
Core feature: simplicity
● Rankar runt 15:e största språk
● Rankade 9 på Github PRs
● Enda språket topp 5 “most wanted” och “most
loved” på Stack Overflow Survey 2017
● Används av ex Dropbox, Cloudflare,
DigitalOcean, Docker, Google
Popularitet
// Separate init and declaration
var i int // will be set to int default (0)
i = 123
var i int = 123 // Above in one line
i := 123 // Shorthand, type inferred (int)
str := “‫”مرحبا‬ // UTF-8 strings
strPtr := &str // & will create pointer to value
var anotherString string
anotherString = *strPtr // * dereferences pointer
const MEETUP_NAME = “Go West”
Types
// map int -> string
myMap := map[int]string{}
myMap[1] = “Go”
// Array of fixed size 3
myArray := [3]string{"Go","West", “introduction”}
myArray[1] // “West”
myArray[10] // panic!
// Non preallocated slice
var mySlice []string // len(mySlice) = 0
mySlice = append(mySlice, “hi”) // len = 1
mySlice[2] = “there” // panic!
// Pre allocated slice
myAllocatedSlice := make([]string, 10) // len 10
myAllocatedSlice[2] = “Hi” // ok!
More complex types
Create types
type Status string // “Fake” enum
const (
Active Status = “active”
Inactive Status = “inactive”
)
type User struct {
Username string
Status Status // instead of string
Profile Profile
}
type Profile struct {
Bio string
}
u := User{
Username: “gust1n”,
Status: Active,
Profile: Profile{
Bio: “Gopher”,
},
}
u.Status = “inactive” // wont compile
Functions
// Simple example
func greet(name string) string {
return “hello ” + name
}
greeting := greet(“Joakim”) // hello Joakim
// Multiple returns
func multiple() (int, int) {
return 0,8
}
first, second := multiple() // first: 0, second: 8
// Variadic functions
func greet(names ...string) {}
greet(“Joakim”, “Susan”, “Ahmed”)
Pointers
u := User{Username: “gust1n”, Status: Inactive}
func activate(u User) {
u.Profile.Status = Active // No effect
}
func activatePtr(u *User) {
u.Profile.Status = Active // Success!
}
func changeUser(u *User) {
u = &User{Username: “Go West”} // No effect
}
activate(u) // u.Profile.Status: Inactive
activatePtr(&u) // u.Profile.Status: Active
changeUser(&u) // u.Profile.Username: gust1n
Methods
func (u *User) activate() {
u.Profile.Status = ACTIVE
}
u := User{Username: “gust1n”, Status: INACTIVE}
u.activate() // Profit!
Concurrency: Blocking
func somethingSlow() {
time.Sleep(10 * time.Second)
fmt.Println(“slow done”)
}
func main() {
somethingSlow()
fmt.Println(“done!”)
}
// output:
// (will wait 10s)
// slow done
// done
// (exit)
Concurrency: go keyword
func somethingSlow() {
time.Sleep(10 * time.Second)
fmt.Println(“slow done”)
}
func main() {
go somethingSlow()
fmt.Println(“done!”)
}
// output:
// done
// (exit)
Concurrency: data races
func calculateTotal(total int, next int) {
total = total + next
}
func main() {
var total int
for i := 0; i < 3; i++ {
go calculateTotal(total, i)
}
fmt.Printf(“total is %d”, total)
}
Concurrency: use mutex?
var lock sync.Mutex
func calculateTotal(total int, next int) {
lock.Lock()
total = total + next
lock.Unlock()
}
func main() {
var total int
for i := 0; i < 3; i++ {
go calculateTotal(total, i)
}
fmt.Printf(“total is %d”, total)
}
Concurrency: channels
// A channel is for communicating between goroutines
intCh := make(chan int, 1)
// A channel can be written to
intCh <- 1337
// and read from (blocking)
i := <- intCh
// Think of it as a pipeline of any type
userCh := make(chan *User, 1)
// Are totally safe for concurrent access
go func() {
intCh <- 1337
}()
Concurrency: orchestration
func calculateNext(resCh chan int, next int) {
resCh <- next
}
func main() {
resCh := make(chan int, 1)
for i := 0; i < 3; i++ {
go calculateNext(resCh, i)
}
var total int
for i := 0; i < 3; i++ {
next := <-resCh // blocks until channel written to
total = total + next
}
fmt.Printf(“total is %d”, total)
}
Concurrency: orchestration cont.
respCh := make(chan int, 1)
doSomethingSlow(respCh)
// blocking
select {
case resp := <-respCh:
// do something with resp
case time.After(2 * time.Second):
// timeout, move on
}
Real world example
package uptime
type Response struct {
URL string
StatusCode int
Duration time.Duration
}
func Check(respCh chan Response, URL string) {
start := time.Now()
resp, _ := http.Get(URL)
respCh <- Response{
URL: URL,
StatusCode:
resp.StatusCode,
Duration: time.Since(start),
}
}
package main
import (
“fmt”
“github.com/gust1n/uptime”
)
func main() {
URLs := []string{
“https://www.golang.org”,
“https://www.rust-lang.org/”,
“http://elixir-lang.github.io/”,
}
respCh := make(chan uptime.Response, 1)
for _, URL := range URLs {
go uptime.Check(respCh, URL)
}
for i := 0; i < len(URLs); i++ {
resp := <- respCh
fmt.Printf(“%s (%d) - %sn”,
resp.URL,
resp.StatusCode,
resp.Duration.String(),
)
}
}

More Related Content

PPTX
Next Generation Language Go
PPTX
Linux basic1&amp;2
PPTX
Introduction to Go
TXT
Facebook Cracker
ODP
Hands on Session on Python
PDF
Git installation
PDF
Swift Study #7
PPTX
Tech Talks - Fundamentos JavaScript
Next Generation Language Go
Linux basic1&amp;2
Introduction to Go
Facebook Cracker
Hands on Session on Python
Git installation
Swift Study #7
Tech Talks - Fundamentos JavaScript

What's hot (20)

PPTX
Monty problem
PDF
Clojure functions
PDF
Asynchronous PHP and Real-time Messaging
PDF
From 0 to mine sweeper in pyside
PDF
Workshop programs
DOC
How to send files to remote server via ssh in php
PDF
React PHP: the NodeJS challenger
ODP
Introduction to Python3 Programming Language
PDF
Groovy as a scripting language
ODP
The promise of asynchronous PHP
PDF
Kotlin의 코루틴은 어떻게 동작하는가
PDF
Learning Rust - experiences from a Python/Javascript developer
PDF
Bash Scripting Workshop
PDF
XML namespaces and XPath with Python
PDF
Absolute Beginners Guide to Puppet Through Types - PuppetConf 2014
PDF
ZeroMQ Is The Answer: DPC 11 Version
PDF
ExtJS勉強会@名古屋
KEY
An introduction to Ruby
PDF
How to stand on the shoulders of giants
PDF
言語の設計判断
Monty problem
Clojure functions
Asynchronous PHP and Real-time Messaging
From 0 to mine sweeper in pyside
Workshop programs
How to send files to remote server via ssh in php
React PHP: the NodeJS challenger
Introduction to Python3 Programming Language
Groovy as a scripting language
The promise of asynchronous PHP
Kotlin의 코루틴은 어떻게 동작하는가
Learning Rust - experiences from a Python/Javascript developer
Bash Scripting Workshop
XML namespaces and XPath with Python
Absolute Beginners Guide to Puppet Through Types - PuppetConf 2014
ZeroMQ Is The Answer: DPC 11 Version
ExtJS勉強会@名古屋
An introduction to Ruby
How to stand on the shoulders of giants
言語の設計判断
Ad

Similar to Lightning talk: Go (20)

PDF
Geeks Anonymes - Le langage Go
KEY
Beauty and Power of Go
PDF
Go serving: Building server app with go
PDF
Using Flow-based programming to write tools and workflows for Scientific Comp...
PDF
Building android apps with kotlin
PDF
Inroduction to golang
PDF
To GO or not to GO
PDF
Introduction to go
PDF
Python-GTK
PDF
Go Lang Tutorial
PDF
Introduction to clojure
PDF
Introduction to python
PDF
Golang workshop
PPTX
ProgrammingwithGOLang
PDF
Python utan-stodhjul-motorsag
PPTX
Golang basics for Java developers - Part 1
PDF
Let's Go-lang
PDF
Easy deployment & management of cloud apps
PDF
05. haskell streaming io
PDF
Groovy for java developers
Geeks Anonymes - Le langage Go
Beauty and Power of Go
Go serving: Building server app with go
Using Flow-based programming to write tools and workflows for Scientific Comp...
Building android apps with kotlin
Inroduction to golang
To GO or not to GO
Introduction to go
Python-GTK
Go Lang Tutorial
Introduction to clojure
Introduction to python
Golang workshop
ProgrammingwithGOLang
Python utan-stodhjul-motorsag
Golang basics for Java developers - Part 1
Let's Go-lang
Easy deployment & management of cloud apps
05. haskell streaming io
Groovy for java developers
Ad

Recently uploaded (20)

PDF
Encapsulation theory and applications.pdf
PPTX
TLE Review Electricity (Electricity).pptx
PDF
Heart disease approach using modified random forest and particle swarm optimi...
PPTX
Spectroscopy.pptx food analysis technology
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Mushroom cultivation and it's methods.pdf
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
August Patch Tuesday
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
PPTX
1. Introduction to Computer Programming.pptx
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
Tartificialntelligence_presentation.pptx
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PPT
Teaching material agriculture food technology
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Encapsulation theory and applications.pdf
TLE Review Electricity (Electricity).pptx
Heart disease approach using modified random forest and particle swarm optimi...
Spectroscopy.pptx food analysis technology
Mobile App Security Testing_ A Comprehensive Guide.pdf
Mushroom cultivation and it's methods.pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
August Patch Tuesday
Diabetes mellitus diagnosis method based random forest with bat algorithm
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
1. Introduction to Computer Programming.pptx
Building Integrated photovoltaic BIPV_UPV.pdf
Tartificialntelligence_presentation.pptx
Encapsulation_ Review paper, used for researhc scholars
NewMind AI Weekly Chronicles - August'25-Week II
Digital-Transformation-Roadmap-for-Companies.pptx
MIND Revenue Release Quarter 2 2025 Press Release
Teaching material agriculture food technology
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf

Lightning talk: Go

  • 2. ● Created by Google for Google scale problems ● First class concurrency support ● Easy to learn, easy to use ● Good performance by default ● C++ too hard, Python too slow, few enjoyed Java Background
  • 3. ● Strong, static typed language ● Garbage Collected ● Compiles to a binary ● Easy cross compilation What is it?
  • 4. Saker Go inte har: ● Klasser ● Konstruktorer/destruktorer ● Ineheritance ● Exceptions ● Annotations ● Generics ● (100% bakåtkompatibelt så länge 1.X) Core feature: simplicity
  • 5. ● Rankar runt 15:e största språk ● Rankade 9 på Github PRs ● Enda språket topp 5 “most wanted” och “most loved” på Stack Overflow Survey 2017 ● Används av ex Dropbox, Cloudflare, DigitalOcean, Docker, Google Popularitet
  • 6. // Separate init and declaration var i int // will be set to int default (0) i = 123 var i int = 123 // Above in one line i := 123 // Shorthand, type inferred (int) str := “‫”مرحبا‬ // UTF-8 strings strPtr := &str // & will create pointer to value var anotherString string anotherString = *strPtr // * dereferences pointer const MEETUP_NAME = “Go West” Types
  • 7. // map int -> string myMap := map[int]string{} myMap[1] = “Go” // Array of fixed size 3 myArray := [3]string{"Go","West", “introduction”} myArray[1] // “West” myArray[10] // panic! // Non preallocated slice var mySlice []string // len(mySlice) = 0 mySlice = append(mySlice, “hi”) // len = 1 mySlice[2] = “there” // panic! // Pre allocated slice myAllocatedSlice := make([]string, 10) // len 10 myAllocatedSlice[2] = “Hi” // ok! More complex types
  • 8. Create types type Status string // “Fake” enum const ( Active Status = “active” Inactive Status = “inactive” ) type User struct { Username string Status Status // instead of string Profile Profile } type Profile struct { Bio string } u := User{ Username: “gust1n”, Status: Active, Profile: Profile{ Bio: “Gopher”, }, } u.Status = “inactive” // wont compile
  • 9. Functions // Simple example func greet(name string) string { return “hello ” + name } greeting := greet(“Joakim”) // hello Joakim // Multiple returns func multiple() (int, int) { return 0,8 } first, second := multiple() // first: 0, second: 8 // Variadic functions func greet(names ...string) {} greet(“Joakim”, “Susan”, “Ahmed”)
  • 10. Pointers u := User{Username: “gust1n”, Status: Inactive} func activate(u User) { u.Profile.Status = Active // No effect } func activatePtr(u *User) { u.Profile.Status = Active // Success! } func changeUser(u *User) { u = &User{Username: “Go West”} // No effect } activate(u) // u.Profile.Status: Inactive activatePtr(&u) // u.Profile.Status: Active changeUser(&u) // u.Profile.Username: gust1n
  • 11. Methods func (u *User) activate() { u.Profile.Status = ACTIVE } u := User{Username: “gust1n”, Status: INACTIVE} u.activate() // Profit!
  • 12. Concurrency: Blocking func somethingSlow() { time.Sleep(10 * time.Second) fmt.Println(“slow done”) } func main() { somethingSlow() fmt.Println(“done!”) } // output: // (will wait 10s) // slow done // done // (exit)
  • 13. Concurrency: go keyword func somethingSlow() { time.Sleep(10 * time.Second) fmt.Println(“slow done”) } func main() { go somethingSlow() fmt.Println(“done!”) } // output: // done // (exit)
  • 14. Concurrency: data races func calculateTotal(total int, next int) { total = total + next } func main() { var total int for i := 0; i < 3; i++ { go calculateTotal(total, i) } fmt.Printf(“total is %d”, total) }
  • 15. Concurrency: use mutex? var lock sync.Mutex func calculateTotal(total int, next int) { lock.Lock() total = total + next lock.Unlock() } func main() { var total int for i := 0; i < 3; i++ { go calculateTotal(total, i) } fmt.Printf(“total is %d”, total) }
  • 16. Concurrency: channels // A channel is for communicating between goroutines intCh := make(chan int, 1) // A channel can be written to intCh <- 1337 // and read from (blocking) i := <- intCh // Think of it as a pipeline of any type userCh := make(chan *User, 1) // Are totally safe for concurrent access go func() { intCh <- 1337 }()
  • 17. Concurrency: orchestration func calculateNext(resCh chan int, next int) { resCh <- next } func main() { resCh := make(chan int, 1) for i := 0; i < 3; i++ { go calculateNext(resCh, i) } var total int for i := 0; i < 3; i++ { next := <-resCh // blocks until channel written to total = total + next } fmt.Printf(“total is %d”, total) }
  • 18. Concurrency: orchestration cont. respCh := make(chan int, 1) doSomethingSlow(respCh) // blocking select { case resp := <-respCh: // do something with resp case time.After(2 * time.Second): // timeout, move on }
  • 19. Real world example package uptime type Response struct { URL string StatusCode int Duration time.Duration } func Check(respCh chan Response, URL string) { start := time.Now() resp, _ := http.Get(URL) respCh <- Response{ URL: URL, StatusCode: resp.StatusCode, Duration: time.Since(start), } } package main import ( “fmt” “github.com/gust1n/uptime” ) func main() { URLs := []string{ “https://www.golang.org”, “https://www.rust-lang.org/”, “http://elixir-lang.github.io/”, } respCh := make(chan uptime.Response, 1) for _, URL := range URLs { go uptime.Check(respCh, URL) } for i := 0; i < len(URLs); i++ { resp := <- respCh fmt.Printf(“%s (%d) - %sn”, resp.URL, resp.StatusCode, resp.Duration.String(), ) } }