SlideShare a Scribd company logo
1 of 19
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

What's hot

言語の設計判断
言語の設計判断言語の設計判断
言語の設計判断
nishio
 

What's hot (20)

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

Similar to Lightning talk: Go

Python-GTK
Python-GTKPython-GTK
Python-GTK
Yuren Ju
 
Python utan-stodhjul-motorsag
Python utan-stodhjul-motorsagPython utan-stodhjul-motorsag
Python utan-stodhjul-motorsag
niklal
 
Easy deployment & management of cloud apps
Easy deployment & management of cloud appsEasy deployment & management of cloud apps
Easy deployment & management of cloud apps
David Cunningham
 

Similar to Lightning talk: Go (20)

Geeks Anonymes - Le langage Go
Geeks Anonymes - Le langage GoGeeks Anonymes - Le langage Go
Geeks Anonymes - Le langage Go
 
Beauty and Power of Go
Beauty and Power of GoBeauty and Power of Go
Beauty and Power of Go
 
Go serving: Building server app with go
Go serving: Building server app with goGo serving: Building server app with go
Go serving: Building server app with go
 
Using Flow-based programming to write tools and workflows for Scientific Comp...
Using Flow-based programming to write tools and workflows for Scientific Comp...Using Flow-based programming to write tools and workflows for Scientific Comp...
Using Flow-based programming to write tools and workflows for Scientific Comp...
 
Building android apps with kotlin
Building android apps with kotlinBuilding android apps with kotlin
Building android apps with kotlin
 
Inroduction to golang
Inroduction to golangInroduction to golang
Inroduction to golang
 
To GO or not to GO
To GO or not to GOTo GO or not to GO
To GO or not to GO
 
Introduction to go
Introduction to goIntroduction to go
Introduction to go
 
Python-GTK
Python-GTKPython-GTK
Python-GTK
 
Go Lang Tutorial
Go Lang TutorialGo Lang Tutorial
Go Lang Tutorial
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojure
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Golang workshop
Golang workshopGolang workshop
Golang workshop
 
ProgrammingwithGOLang
ProgrammingwithGOLangProgrammingwithGOLang
ProgrammingwithGOLang
 
Python utan-stodhjul-motorsag
Python utan-stodhjul-motorsagPython utan-stodhjul-motorsag
Python utan-stodhjul-motorsag
 
Golang basics for Java developers - Part 1
Golang basics for Java developers - Part 1Golang basics for Java developers - Part 1
Golang basics for Java developers - Part 1
 
Let's Go-lang
Let's Go-langLet's Go-lang
Let's Go-lang
 
Easy deployment & management of cloud apps
Easy deployment & management of cloud appsEasy deployment & management of cloud apps
Easy deployment & management of cloud apps
 
05. haskell streaming io
05. haskell streaming io05. haskell streaming io
05. haskell streaming io
 
Groovy for java developers
Groovy for java developersGroovy for java developers
Groovy for java developers
 

Recently uploaded

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Recently uploaded (20)

Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 

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(), ) } }