SlideShare una empresa de Scribd logo
1 de 48
04.07.2017
Fatih Şimşek - Software Infrastructure
GoLang
GoLang
Open Source
Huge community
Robert Griesemer, Rob Pike, Ken Thompson
Started at late 2009
1.0v published in March 2012
1.8v published in February 2017
•Go 1.8 (February 2017)
Designers
•Go 1.8 (February 2017)
All Team: https://www.youtube.com/watch?v=sln-gJaURzk
Scale at Google
System Scale
• Designed to scale to 106+ machines
• Everyday jobs run on 1000s machines
• Job coordinate, interacting with others in the system
• Lots going on at once
Solution: great support for concurrency
Scale at Google
Engineering Scale
• 500+ developers across 40+ offices
• 20+ changes per minute
• 50% of code base changes every month
• 50 million test cases executed per day
• Single code tree
Solution: design the language for large code bases
Pain Points
Slow Build Cross-language builds
Code hard to read Uncontrolled Dependencies
Each programmer using a different
subset of th language
Cost of updates
Version skew
Difficult of writing automatic tools
Why GoLang?
Simple (25 keywords)
Fast compiled, Modern
Compile into one executable file
Static Type-Checked, Fast Compiled
Garbage-Collected
Built-in Concurrency
•Go 1.8 (February 2017)
When to use Go?
System programming
Web apps
CLI based apps
Games
Scientific Apps
•Go 1.8 (February 2017)
Github
Who uses Go?
https://github.com/golang/go/wiki/GoUsers
Google Dropbox SoundCloud
IBM eBay TIBCO
Twitter Medium Uber
Facebook Github WMware
Yahoo Pinterest Yandex
Success Stories
Dailymotion: We like its simplicity, its performance and its static
type checking.
Dropbox: We decided to migrate our performance-critical backends
from Python to Go to leverage better concurrency support and faster
execution speed
Uber: We are extremely happy with our decision to Go for it and
write our service in a new language. Go typically takes just a few days
for a C++, Java or Node.js developer to learn, and the code is easy to
maintain
Tumblr: Go is an ideal language for writing web servers. It’s compiled
and integrates seamlessly with C libraries.
Success Stories
MongoDB: The Backup Service started as a Java project, but as the
project matured, the team wanted to move to a language that
compiled natively on the machine. After considering a few options,
the team decided that Go was the best fit.
Medium: Our Neo4j database is managed by a service written in Go.
Cloudfare: Go's concurrency makes writing software that must scale
up and down very easy.
Developement Environment
Sublime Text
Atom
Visual Studio Code
Intellij
Netbeans
Eclipse
Visual Studio Code with GoLang
https://golang.org/dl/
Delve debugger
go get github.com/derekparker/delve/cmd/dlv
Install Go extension for Visual Studio Code
DEMO
Types
Built-in Types:
Variables
• var i int var (
• var f float64 = 1.5 counter int64
• var b bool = true wg sync.WaitGroup
• var s string = "golang" )
Shortcut:
• i := 10
• s := "golang"
• f := 1.5
• b := false
No implicit numeric conversions
Array
Array bounds are always checked
var days [7]string
var board [4][2]int
var val [5]int = [5]int { 44, 72, 16, 1, 5 }
var counts = [...]int { 2,4,5,6 }
var scores = [5]int {1: 10, 2: 20}
Array
Passing an array between functions can be an expensive
operation in terms of memory and performance.
var array [8]int var array [8]int
foo(array) foo(&array)
func foo(array [8]int) { func foo(array *[8]int) {
... ...
} }
Passing pointer of array is only copy eight bytes.
Slice
Slices are built around the concept of dynamic arrays that can
grow and shrink
slice := make([]string, 5)
slice := []string{"Red", "Blue", "Green", "Yellow", "Pink"}
newSlice := slice[1:3]
newSlice = append(newSlice, 60)
Map
Maps don’t have a capacity or any restriction on growth
colors := map[string]string{}
colors["Red"] = "#da1337"
value, exists := colors["Blue"]
for key, value := range colors {
fmt.Printf("Key: %s Value: %sn", key, value)
}
func printColor(colors map[string]string) {
...
}
Function
func [<func-identifier>] ([<argument-list>]) [(<result-list>)] {
return [<value or expression list>]
}
func add(op0 int, op1 int) int {
return op0 + op1
}
func main() {
var opAdd func(int, int) = add
opAdd2 := add
}
Function
Variadic Functions:
func avg(nums ...float64) int
Return Parameters:
func div(op0, op1 int) (int, int) {
return q, r
}
func div(op0, op1 int) (q,r int) {
return
}
Function
Pass by reference:
func half(val *float64) {
*val = *val / 2
}
func main() {
num :=2.8
half(&num)
rad := func() float64 {
return 5 * math.Pi / 180
}()
}
Pointer
Similar to C/C++, Go uses the * operator to designate a type as
a pointer
var countPtr *int
var row []*int64
var a int = 1024
var aptr *int = &a
Unlike C, Go runtime maintains control of the management of
pointers at runtime. A programmer cannot add an arbitrary
integer value to the pointer to generate a new pointer address
OOP
struct Class with fields, only non-virtual methods
interface Class with only virtual methods
embedding Multiple inheritance and composition
Struct
No Constructor:
type user struct {
name string
email string
ext int
}
lisa := user {
name: "Lisa",
email: "lisa@email.com",
ext: 123
}
lisa := user{"Lisa", "lisa@email.com", 123}
Struct
No Inheritance / Composition:
type admin struct {
person user
level string
}
fred := admin {
person: user {
name: "Lisa",
email: "lisa@email.com",
ext: 123
},
level: "super"
}
Struct
No Inheritance / Embedding:
type Animal struct { type Dog struct {
legCount int Animal
} }
func (anm Animal) numberOfLegs int {
return anm.legCount
}
func main() {
d: = Dog(Animal(4))
fmt.Println("Leg count: %s", d.numberofLegs())
}
Interface
Implement all methods in interface:
type geometry interface { func main() {
area() float64 r: rect{ width:3, height:4 }
} measure(r)
type rect struct { }
width, height float64
}
func (r rect) area() float64 {
return r.width * r.height
}
func measure(g geometry) {
fmt.Println(g.area())
}
Packages
Name of the identifier itself carries the visibility
• Upper case : Public / exported / visible to other packages
• Lower case : Private to the package
import (
[identifier] "<path>"
)
import "fmt "
import vpr "github.com/spf13/viper"
import . "foo/bar/util/logger"
init(): function is invoked after the package-level variables are initialized
Error Handling
defer:
Pushing function to internal stack, delaying its execution
right before the enclosing function returns
• Closing open files
• Releasing network resources
• Closing channel
• Commiting database transactions
• Error handling
Error Handling
panic / recover:
func main() {
panicAndRecover()
fmt.Println("I need to run the statement at any cost!")
}
func panicAndRecover() {
defer func() {
if err := recover(); err != nil {
fmt.Println(err)
}
}()
panic("Unable to connect database!")
}
DEMO
Concurrency
When a function is created as a goroutine, it’s treated as an
independent unit of work that gets scheduled and then
executed on an available logical processor
The Go runtime scheduler is a sophisticated piece of software
that manages all the goroutines that are created and need
processor time
The scheduler sits on top of the operating system, binding
operating system’s threads to logical processors which, in turn,
execute goroutines
Concurrency
Concurrency vs Parallelism
Goroutine
runtime.GOMAXPROCS(1)
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
....
}
fmt.Println("Waiting for Finish")
wg.Wait()
Race Conditions
Go has a special tool that can detect race conditions in your
code.
go build –race //Build the code using the racind detector
./example //Run the code
------------------------------
WARNING: DATE RACE
Write by goroutine: 5
main.incCounter()
/example/main.go:49 +0x96
Previous read by goroutine 6:
main.main()
/example/main.go:49 +0x66
Locking
Go provides traditional support to synchronize goroutines by
locking access to shared resources
atomic.AddInt64(&counter, 1)
atomic.LoadInt64(&counter)
atomic.StoreInt64(&counter,1)
mutex.Lock() {
....
}
mutex.UnLock()
Channel
Don’t communicate by sharing memory, share memory by
communicating
Synchronize goroutines as they send and receive the resources
they need to share between each other
unbuffered := make(chan int)
buffered := make(chan string, 10)
value := <- buffered
buffered <- value
UnBuffered Channel
Buffered Channel
Garbage Collection
Go 1.5:
• Concurrent
• Low latency
Garbage Collection
Tricolor Algorithm:
Initially color all nodes white (unexplored)
Color the root gray.
while some gray node x exist
color some white successors of x gray
if x has no successors left, color it black
Breadth-First
Mark and Sweep
Limit GC latency to less than 10 miliseconds
DEMO
Golang

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

Golang workshop
Golang workshopGolang workshop
Golang workshop
 
Introduction to go lang
Introduction to go langIntroduction to go lang
Introduction to go lang
 
Go Programming Language (Golang)
Go Programming Language (Golang)Go Programming Language (Golang)
Go Programming Language (Golang)
 
Introduction to Go programming language
Introduction to Go programming languageIntroduction to Go programming language
Introduction to Go programming language
 
Go lang
Go langGo lang
Go lang
 
Golang - Overview of Go (golang) Language
Golang - Overview of Go (golang) LanguageGolang - Overview of Go (golang) Language
Golang - Overview of Go (golang) Language
 
An introduction to programming in Go
An introduction to programming in GoAn introduction to programming in Go
An introduction to programming in Go
 
Introduction to GoLang
Introduction to GoLangIntroduction to GoLang
Introduction to GoLang
 
GoLang Introduction
GoLang IntroductionGoLang Introduction
GoLang Introduction
 
Golang (Go Programming Language)
Golang (Go Programming Language)Golang (Go Programming Language)
Golang (Go Programming Language)
 
The Go programming language - Intro by MyLittleAdventure
The Go programming language - Intro by MyLittleAdventureThe Go programming language - Intro by MyLittleAdventure
The Go programming language - Intro by MyLittleAdventure
 
Introduction to Go language
Introduction to Go languageIntroduction to Go language
Introduction to Go language
 
Write microservice in golang
Write microservice in golangWrite microservice in golang
Write microservice in golang
 
Go Programming Language by Google
Go Programming Language by GoogleGo Programming Language by Google
Go Programming Language by Google
 
Golang and Eco-System Introduction / Overview
Golang and Eco-System Introduction / OverviewGolang and Eco-System Introduction / Overview
Golang and Eco-System Introduction / Overview
 
Go Lang Tutorial
Go Lang TutorialGo Lang Tutorial
Go Lang Tutorial
 
Golang getting started
Golang getting startedGolang getting started
Golang getting started
 
GO programming language
GO programming languageGO programming language
GO programming language
 
Go Concurrency
Go ConcurrencyGo Concurrency
Go Concurrency
 
Goroutines and Channels in practice
Goroutines and Channels in practiceGoroutines and Channels in practice
Goroutines and Channels in practice
 

Similar a Golang

これからのPerlプロダクトのかたち(YAPC::Asia 2013)
これからのPerlプロダクトのかたち(YAPC::Asia 2013)これからのPerlプロダクトのかたち(YAPC::Asia 2013)
これからのPerlプロダクトのかたち(YAPC::Asia 2013)
goccy
 

Similar a Golang (20)

Build Great Networked APIs with Swift, OpenAPI, and gRPC
Build Great Networked APIs with Swift, OpenAPI, and gRPCBuild Great Networked APIs with Swift, OpenAPI, and gRPC
Build Great Networked APIs with Swift, OpenAPI, and gRPC
 
EKON 25 Python4Delphi_mX4
EKON 25 Python4Delphi_mX4EKON 25 Python4Delphi_mX4
EKON 25 Python4Delphi_mX4
 
Go from a PHP Perspective
Go from a PHP PerspectiveGo from a PHP Perspective
Go from a PHP Perspective
 
これからのPerlプロダクトのかたち(YAPC::Asia 2013)
これからのPerlプロダクトのかたち(YAPC::Asia 2013)これからのPerlプロダクトのかたち(YAPC::Asia 2013)
これからのPerlプロダクトのかたち(YAPC::Asia 2013)
 
Go fundamentals
Go fundamentalsGo fundamentals
Go fundamentals
 
MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides:  Let's build macOS CLI Utilities using SwiftMobileConf 2021 Slides:  Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift
 
Griffon for the Enterprise
Griffon for the EnterpriseGriffon for the Enterprise
Griffon for the Enterprise
 
Designing flexible apps deployable to App Engine, Cloud Functions, or Cloud Run
Designing flexible apps deployable to App Engine, Cloud Functions, or Cloud RunDesigning flexible apps deployable to App Engine, Cloud Functions, or Cloud Run
Designing flexible apps deployable to App Engine, Cloud Functions, or Cloud Run
 
Introduction to Software Development
Introduction to Software DevelopmentIntroduction to Software Development
Introduction to Software Development
 
Reproducibility and automation of machine learning process
Reproducibility and automation of machine learning processReproducibility and automation of machine learning process
Reproducibility and automation of machine learning process
 
The why and how of moving to php 7.x
The why and how of moving to php 7.xThe why and how of moving to php 7.x
The why and how of moving to php 7.x
 
Mender.io | Develop embedded applications faster | Comparing C and Golang
Mender.io | Develop embedded applications faster | Comparing C and GolangMender.io | Develop embedded applications faster | Comparing C and Golang
Mender.io | Develop embedded applications faster | Comparing C and Golang
 
Go. why it goes v2
Go. why it goes v2Go. why it goes v2
Go. why it goes v2
 
The why and how of moving to php 7.x
The why and how of moving to php 7.xThe why and how of moving to php 7.x
The why and how of moving to php 7.x
 
Next .NET and C#
Next .NET and C#Next .NET and C#
Next .NET and C#
 
"Building, deploying and running production code at Dropbox" Васильев Леонид,...
"Building, deploying and running production code at Dropbox" Васильев Леонид,..."Building, deploying and running production code at Dropbox" Васильев Леонид,...
"Building, deploying and running production code at Dropbox" Васильев Леонид,...
 
Project Flogo: An Event-Driven Stack for the Enterprise
Project Flogo: An Event-Driven Stack for the EnterpriseProject Flogo: An Event-Driven Stack for the Enterprise
Project Flogo: An Event-Driven Stack for the Enterprise
 
The why and how of moving to php 8
The why and how of moving to php 8The why and how of moving to php 8
The why and how of moving to php 8
 
Practices and Tools for Building Better APIs
Practices and Tools for Building Better APIsPractices and Tools for Building Better APIs
Practices and Tools for Building Better APIs
 
Inroduction to golang
Inroduction to golangInroduction to golang
Inroduction to golang
 

Más de Software Infrastructure

Más de Software Infrastructure (20)

Kotlin
KotlinKotlin
Kotlin
 
NoSql
NoSqlNoSql
NoSql
 
Stream Analytics
Stream AnalyticsStream Analytics
Stream Analytics
 
Quartz Scheduler
Quartz SchedulerQuartz Scheduler
Quartz Scheduler
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Deep Learning
Deep Learning Deep Learning
Deep Learning
 
Progressive Web Apps
Progressive Web AppsProgressive Web Apps
Progressive Web Apps
 
Java9
Java9Java9
Java9
 
Machine learning
Machine learningMachine learning
Machine learning
 
Raspberry PI
Raspberry PIRaspberry PI
Raspberry PI
 
Codename one
Codename oneCodename one
Codename one
 
Hazelcast sunum
Hazelcast sunumHazelcast sunum
Hazelcast sunum
 
Microsoft bot framework
Microsoft bot frameworkMicrosoft bot framework
Microsoft bot framework
 
Blockchain use cases
Blockchain use casesBlockchain use cases
Blockchain use cases
 
The Fintechs
The FintechsThe Fintechs
The Fintechs
 
Server Side Swift
Server Side SwiftServer Side Swift
Server Side Swift
 
Push Notification
Push NotificationPush Notification
Push Notification
 
.Net Core
.Net Core.Net Core
.Net Core
 
Java Batch
Java BatchJava Batch
Java Batch
 
Big Data & Hadoop
Big Data & HadoopBig Data & Hadoop
Big Data & Hadoop
 

Último

AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
ankushspencer015
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Dr.Costas Sachpazis
 

Último (20)

Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdf
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduits
 
Glass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesGlass Ceramics: Processing and Properties
Glass Ceramics: Processing and Properties
 
NFPA 5000 2024 standard .
NFPA 5000 2024 standard                                  .NFPA 5000 2024 standard                                  .
NFPA 5000 2024 standard .
 
UNIT-IFLUID PROPERTIES & FLOW CHARACTERISTICS
UNIT-IFLUID PROPERTIES & FLOW CHARACTERISTICSUNIT-IFLUID PROPERTIES & FLOW CHARACTERISTICS
UNIT-IFLUID PROPERTIES & FLOW CHARACTERISTICS
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineering
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 

Golang

  • 1. 04.07.2017 Fatih Şimşek - Software Infrastructure GoLang
  • 2. GoLang Open Source Huge community Robert Griesemer, Rob Pike, Ken Thompson Started at late 2009 1.0v published in March 2012 1.8v published in February 2017 •Go 1.8 (February 2017)
  • 3. Designers •Go 1.8 (February 2017) All Team: https://www.youtube.com/watch?v=sln-gJaURzk
  • 4. Scale at Google System Scale • Designed to scale to 106+ machines • Everyday jobs run on 1000s machines • Job coordinate, interacting with others in the system • Lots going on at once Solution: great support for concurrency
  • 5. Scale at Google Engineering Scale • 500+ developers across 40+ offices • 20+ changes per minute • 50% of code base changes every month • 50 million test cases executed per day • Single code tree Solution: design the language for large code bases
  • 6. Pain Points Slow Build Cross-language builds Code hard to read Uncontrolled Dependencies Each programmer using a different subset of th language Cost of updates Version skew Difficult of writing automatic tools
  • 7. Why GoLang? Simple (25 keywords) Fast compiled, Modern Compile into one executable file Static Type-Checked, Fast Compiled Garbage-Collected Built-in Concurrency •Go 1.8 (February 2017)
  • 8. When to use Go? System programming Web apps CLI based apps Games Scientific Apps •Go 1.8 (February 2017)
  • 10. Who uses Go? https://github.com/golang/go/wiki/GoUsers Google Dropbox SoundCloud IBM eBay TIBCO Twitter Medium Uber Facebook Github WMware Yahoo Pinterest Yandex
  • 11. Success Stories Dailymotion: We like its simplicity, its performance and its static type checking. Dropbox: We decided to migrate our performance-critical backends from Python to Go to leverage better concurrency support and faster execution speed Uber: We are extremely happy with our decision to Go for it and write our service in a new language. Go typically takes just a few days for a C++, Java or Node.js developer to learn, and the code is easy to maintain Tumblr: Go is an ideal language for writing web servers. It’s compiled and integrates seamlessly with C libraries.
  • 12. Success Stories MongoDB: The Backup Service started as a Java project, but as the project matured, the team wanted to move to a language that compiled natively on the machine. After considering a few options, the team decided that Go was the best fit. Medium: Our Neo4j database is managed by a service written in Go. Cloudfare: Go's concurrency makes writing software that must scale up and down very easy.
  • 13. Developement Environment Sublime Text Atom Visual Studio Code Intellij Netbeans Eclipse
  • 14. Visual Studio Code with GoLang https://golang.org/dl/ Delve debugger go get github.com/derekparker/delve/cmd/dlv Install Go extension for Visual Studio Code
  • 15. DEMO
  • 17. Variables • var i int var ( • var f float64 = 1.5 counter int64 • var b bool = true wg sync.WaitGroup • var s string = "golang" ) Shortcut: • i := 10 • s := "golang" • f := 1.5 • b := false No implicit numeric conversions
  • 18. Array Array bounds are always checked var days [7]string var board [4][2]int var val [5]int = [5]int { 44, 72, 16, 1, 5 } var counts = [...]int { 2,4,5,6 } var scores = [5]int {1: 10, 2: 20}
  • 19. Array Passing an array between functions can be an expensive operation in terms of memory and performance. var array [8]int var array [8]int foo(array) foo(&array) func foo(array [8]int) { func foo(array *[8]int) { ... ... } } Passing pointer of array is only copy eight bytes.
  • 20. Slice Slices are built around the concept of dynamic arrays that can grow and shrink slice := make([]string, 5) slice := []string{"Red", "Blue", "Green", "Yellow", "Pink"} newSlice := slice[1:3] newSlice = append(newSlice, 60)
  • 21. Map Maps don’t have a capacity or any restriction on growth colors := map[string]string{} colors["Red"] = "#da1337" value, exists := colors["Blue"] for key, value := range colors { fmt.Printf("Key: %s Value: %sn", key, value) } func printColor(colors map[string]string) { ... }
  • 22. Function func [<func-identifier>] ([<argument-list>]) [(<result-list>)] { return [<value or expression list>] } func add(op0 int, op1 int) int { return op0 + op1 } func main() { var opAdd func(int, int) = add opAdd2 := add }
  • 23. Function Variadic Functions: func avg(nums ...float64) int Return Parameters: func div(op0, op1 int) (int, int) { return q, r } func div(op0, op1 int) (q,r int) { return }
  • 24. Function Pass by reference: func half(val *float64) { *val = *val / 2 } func main() { num :=2.8 half(&num) rad := func() float64 { return 5 * math.Pi / 180 }() }
  • 25. Pointer Similar to C/C++, Go uses the * operator to designate a type as a pointer var countPtr *int var row []*int64 var a int = 1024 var aptr *int = &a Unlike C, Go runtime maintains control of the management of pointers at runtime. A programmer cannot add an arbitrary integer value to the pointer to generate a new pointer address
  • 26. OOP struct Class with fields, only non-virtual methods interface Class with only virtual methods embedding Multiple inheritance and composition
  • 27. Struct No Constructor: type user struct { name string email string ext int } lisa := user { name: "Lisa", email: "lisa@email.com", ext: 123 } lisa := user{"Lisa", "lisa@email.com", 123}
  • 28. Struct No Inheritance / Composition: type admin struct { person user level string } fred := admin { person: user { name: "Lisa", email: "lisa@email.com", ext: 123 }, level: "super" }
  • 29. Struct No Inheritance / Embedding: type Animal struct { type Dog struct { legCount int Animal } } func (anm Animal) numberOfLegs int { return anm.legCount } func main() { d: = Dog(Animal(4)) fmt.Println("Leg count: %s", d.numberofLegs()) }
  • 30. Interface Implement all methods in interface: type geometry interface { func main() { area() float64 r: rect{ width:3, height:4 } } measure(r) type rect struct { } width, height float64 } func (r rect) area() float64 { return r.width * r.height } func measure(g geometry) { fmt.Println(g.area()) }
  • 31. Packages Name of the identifier itself carries the visibility • Upper case : Public / exported / visible to other packages • Lower case : Private to the package import ( [identifier] "<path>" ) import "fmt " import vpr "github.com/spf13/viper" import . "foo/bar/util/logger" init(): function is invoked after the package-level variables are initialized
  • 32. Error Handling defer: Pushing function to internal stack, delaying its execution right before the enclosing function returns • Closing open files • Releasing network resources • Closing channel • Commiting database transactions • Error handling
  • 33. Error Handling panic / recover: func main() { panicAndRecover() fmt.Println("I need to run the statement at any cost!") } func panicAndRecover() { defer func() { if err := recover(); err != nil { fmt.Println(err) } }() panic("Unable to connect database!") }
  • 34. DEMO
  • 35.
  • 36. Concurrency When a function is created as a goroutine, it’s treated as an independent unit of work that gets scheduled and then executed on an available logical processor The Go runtime scheduler is a sophisticated piece of software that manages all the goroutines that are created and need processor time The scheduler sits on top of the operating system, binding operating system’s threads to logical processors which, in turn, execute goroutines
  • 39. Goroutine runtime.GOMAXPROCS(1) var wg sync.WaitGroup wg.Add(2) go func() { defer wg.Done() .... } fmt.Println("Waiting for Finish") wg.Wait()
  • 40. Race Conditions Go has a special tool that can detect race conditions in your code. go build –race //Build the code using the racind detector ./example //Run the code ------------------------------ WARNING: DATE RACE Write by goroutine: 5 main.incCounter() /example/main.go:49 +0x96 Previous read by goroutine 6: main.main() /example/main.go:49 +0x66
  • 41. Locking Go provides traditional support to synchronize goroutines by locking access to shared resources atomic.AddInt64(&counter, 1) atomic.LoadInt64(&counter) atomic.StoreInt64(&counter,1) mutex.Lock() { .... } mutex.UnLock()
  • 42. Channel Don’t communicate by sharing memory, share memory by communicating Synchronize goroutines as they send and receive the resources they need to share between each other unbuffered := make(chan int) buffered := make(chan string, 10) value := <- buffered buffered <- value
  • 45. Garbage Collection Go 1.5: • Concurrent • Low latency
  • 46. Garbage Collection Tricolor Algorithm: Initially color all nodes white (unexplored) Color the root gray. while some gray node x exist color some white successors of x gray if x has no successors left, color it black Breadth-First Mark and Sweep Limit GC latency to less than 10 miliseconds
  • 47. DEMO

Notas del editor

  1. 1.9v is expected to released in August, 2017. Now Rc2 Parallel Compilation  The Go compiler now supports compiling a package's functions in parallel, taking advantage of multiple cores. This is in addition to the go command's existing support for parallel compilation of separate packages. Parallel compilation is on by default, but can be disabled by setting the environment variable GO19CONCURRENTCOMPILATIONto 0.
  2. Go team ( https://www.youtube.com/watch?v=sln-gJaURzk )
  3. https://talks.golang.org/2012/splash.article
  4. C, C++ written build server takes 45 minutes. ( include library ), With Go takes 5 minutes (Splash 2012 conf) C open header file recursively so I/O so much
  5. https://play.golang.org/
  6. Syntax ( Hello SGM )
  7. Every time the function foo is called, eight megabytes of memory has to be allocated on the stack. Then the value of the array, all eight megabytes of memory, has to be copied into that allocation. Go can handle this copy operation, but there’s a better and more efficient way of doing this. You can pass a pointer to the array and only copy eight bytes, instead of eight megabytes of memory on the stack This time the function foo takes a pointer to an array of one million elements of type integer. The function call now passes the address of the array, which only requires eight bytes of memory to be allocated on the stack for the pointer variable.
  8. // Contains a length of 2 and capacity of 4 elements. newSlice := slice[1:3] (20,30) For slice[i:j] with an underlying array of capacity k Length: j - i Capacity: k – I For slice[1:3] with an underlying array of capacity 5 Length: 3 - 1 = 2 Capacity: 5 - 1 = 4 The append operation is clever when growing the capacity of the underlying array. Capacity is always doubled when the existing capacity of the slice is under 1,000 elements. Once the number of elements goes over 1,000, the capacity is grown by a factor of 1.25, or 25%. This growth algorithm may change in the language over time.
  9. This in itself isn't enough to replace inheritance, as embedding provides no form of polymorphism. In other languages, inheritance hierarchies need to be carefully designed because changes are wide sweeping and therefore hard to do. Go avoids these pitfalls while providing a powerful alternative. Shadowing: defining another function or field with the same name Type Base struct { X.A //int A string X.Base.A //string B float64 X.B //float64 } Type Derived struct { Base A int }
  10. To implement an interface in Go, we just need to implement all the methods in the interface. Here we implement geometry on rects.
  11. When an import statement uses the dot identifier (.) for an import path, it causes members of the imported package to be merged in scope with that of the importing package. Therefore, imported members may be referenced without additional qualifiers
  12. Sometimes a running goroutine may need to perform a blocking syscall, such as opening a file. When this happens, the thread and goroutine are detached from the logical processor and the thread continues to block waiting for the syscall to return. In the meantime, there’s a logical processor without a thread. So the scheduler creates a new thread and attaches it to the logical processor. Then the scheduler will choose another goroutine from the local run queue for execution. Once the syscall returns, the goroutine is placed back into a local run queue, and the thread is put aside for future use. If a goroutine needs to make a network I/O call, the process is a bit different. In this case, the goroutine is detached from the logical processor and moved to the runtime integrated network poller. Once the poller indicates a read or write operation is ready, the goroutine is assigned back to a logical processor to handle the operation There’s no restriction built into the scheduler for the number of logical processors that can be created. But the runtime limits each program to a maximum of 10,000 threads by default. This value can be changed by calling the SetMaxThreads function from the runtime/debug package. If any program attempts to use more threads, the program crashes.
  13. Concurrency is not parallelism. Parallelism can only be achieved when multiple pieces of code are executing simultaneously against different physical processors. Parallelism is about doing a lot of things at once. Concurrency is about managing a lot of things at once. In many cases, concurrency can outperform parallelism, because the strain on the operating system and hardware is much less, which allows the system to do more If you want to run goroutines in parallel, you must use more than one logical processor. When there are multiple logical processors, the scheduler will evenly distribute goroutines between the logical processors. This will result in goroutines running on different threads It’s not recommended to blindly change the runtime default for a logical processor. The scheduler contains intelligent algorithms that are updated and improved with every release of Go
  14. An unbuffered channel is a channel with no capacity to hold any value before it’s received. These types of channels require both a sending and receiving goroutine to be ready at the same instant before any send or receive operation can complete. If the two goroutines aren’t ready at the same instant, the channel makes the goroutine that performs its respective send or receive operation first wait In step 1 the two goroutines approach the channel, but neither have issued a send or receive yet. In step 2 the goroutine on the left sticks its hand into the channel, which simulates a send on the channel. At this point, that goroutine is locked in the channel until the exchange is complete. In step 3 the goroutine on the right places its hand into the channel, which simulates a receive on the channel. That goroutine is now locked in the channel until the exchange is complete. In steps 4 and 5 the exchange is made and finally, in step 6, both goroutines are free to remove their hands, which simulates the release of the locks.
  15. A buffered channel is a channel with capacity to hold one or more values before they’re received. These types of channels don’t force goroutines to be ready at the same instant to perform sends and receives. There are also different conditions for when a send or receive does block. A receive will block only if there’s no value in the channel to receive. A send will block only if there’s no available buffer to place the value being sent. This leads to the one big difference between unbuffered and buffered channels: An unbuffered channel provides a guarantee that an exchange between two goroutines is performed at the instant the send and receive take place. A buffered channel has no such guarantee. In step 1 the goroutine on the right is in the process of receiving a value from the channel. In step 2 that same goroutine is able to complete the receive independent of the goroutine on the left sending a new value into the channel. In step 3 the goroutine on the left is sending a new value into the channel while the goroutine on the right is receiving a different value. Neither of these two operations in step 3 are in sync with each other or blocking. Finally, in step 4 all the sends and receives are complete and we have a channel with several values and room for more.
  16. Two types of garbage collector: Reference Counting: Each object has a count of other objects referencing it Sensitive to cycle referencing Not real-time Must be atomic Increasing space overhead Tracing garbage collector: Determine which objects are reachable from a certain «root» object Unreachable objects are considerable as garbage