SlideShare a Scribd company logo
1 of 62
Download to read offline
How To Think In Go
or, let me tell you about all the ways I screwed up
https://www.flickr.com/photos/spam/3355824586
Panics and Errors
“Oh look, panic() and rescue()! I can
probably use it like lightweight
exceptions!”
Misconception
! panic: unrecoverable errors
! error: recoverable errors
panic / error
sub foo {
eval {
might_die();
};
if ($@) {
# handle $@
}
important_task();
}
Perl: Exceptions
func main() {
defer func() {
if err := recover(); err != nil {
// handle err
}
}()
mightPanic()
importantTask() // Never reached if mightPanic() panics
}
A bad port
func mightPanic() {
defer func() {
if err := recover(); err != nil {
// handle err
}
}()
panic(“BOO!”)
}
func main() {
mightPanic()
importantTask()
}
Attempt #2
func main() {
if err := tryit(mightPanic); err != nil {
fmt.Printf(“Found error: %sn”, err)
}
importantTask()
}
func mightPanic() {
panic(“BOO!”)
}
Attempt #3
func tryit(code func()) (err error) {
    defer func() {
        if e := recover(); e != nil {
            var ok bool
            if err, ok = e.(error); !ok {
                err = fmt.Errorf("%s", e)
            }
        }
    }()
    code()
    return err
}
Attempt #3
“Why don’t I just use plain errors to
begin with?”
Go Way
func mightError() error {
     if errorCase {
          return errors.New(“error case 1”)
     }
     if err := someOtherThingMightError(); err != nil {
          // propagate error
          return err
     }
     return nil
}
Use errors!
func main() {
     if err := mightError(); err != nil {
         // handle it
     }
     importantTask()
}
Use errors!
! Do not dream about exceptions
! Do stick with errors
Use errors!
Concurrency
“Go’s makes concurrency so easy, we
can just port our multi-process code in
an instant!”
Misconception
! PIDs to identify processes
! Processes can be signaled
! Processes can notify termination
Processes
! No pid to identify goroutines
! No signals to communicate
! Goroutines don’t notify on exit
Goroutine
sub sub main {
     my $pid = fork();
     if (! defined $pid) { die “Failed to fork: $!” }
     if (! $pid) { while(1) { do_stuff() } }
     $SIG{CHLD} = sub {
           my $pid = wait;
           print “reaped $pidn”;
     };
     sleep 5;
     kill TERM => $pid;
     while (kill 0 => $pid) { sleep 1 }
}
Perl: Processes
func main() { // Won’t work
    go func() {
for {
doStuff()
}
}
}
Go: A simple goroutine
func main() {
    exitCh := make(chan struct{})
go func() {
defer func() { close(exitCh) }() // close upon termination
for {
doStuff()
}
}
<-exitCh // Wait for something to happen
}
Go: Detect termination
func main() {
    exitCh := make(chan struct{})
incomingCh := make(chan struct{})
go func() {
defer func() { close(exitCh) }() // close upon termination
for {
select {
case <-incomingCh: // Got termination request
return
}
doStuff()
}
}
Go:Accept Termination Request
// Send request to terminate loop
time.AfterFunc(5 * time.Second, func() {
incomingCh <-struct{}{}
})
<-exitCh // Wait for something to happen
}
Go:Accept Termination Request
! Explicit coordination required
! No goroutine specific storage
Goroutine
! You must explicitly bail out for
infinite loops in goroutines
One more thing:
! Still, goroutines are worth it
! Channels can do much more
Too much hassle?
Designing Structures
“Structs and methods will allow us to
make our Object-oriented code easy to
port”
Misconception
Worker::Base
Worker::Foo Worker::Foo Worker::Foo
package Worker::Base;
# snip
sub foo {
# do stuff..
shift->something_overridable_in_child_class();
}
sub something_overridable_in_child_class { … }
Perl: Interaction Between Parent/Child
package Worker::Foo;
# snip
use parent qw(Worker::Base);
sub something_overridable_in_child_class { … }
sub work {
my $self = shift;
while (1) {
# do stuff…
$self->foo(); # Doesn’t translate very well into Go
}
}
Perl: Interaction Between Parent/Child
! No. Just No.
! Embedded structs + Automatic Delegation
Go: No Inheritance
type Name string
func (n Name) Greet() string {
return fmt.Sprintf(“Hello, my name is %s”, n)
}
Go: Name
n := Name(“Daisuke Maki”)
println(n.Greet()) // “Hello, my name is Daisuke Maki”
Go: Name
type Person struct {
Name // Embedded struct
Age uint // A regular field
}
Go: Person
p := &Person{
Name: Name(“Daisuke Maki”),
Age: 38
}
println(p.Greet()) // “Hello, my name is Daisuke Maki”
Go: Automatic Delegation
p.Greet() // → p.Name.Greet()
// The receiver is p.Name, not p.
Go: Automatic Delegation
func (p Person) Greet() string {
return fmt.Sprintf(
“%s. I’m %d years old”,
p.Super.Greet(), // Pseudo-code. Doesn’t work
p.Age,
)
}
Go: Customizing Person.Greet()
type BaseWorker struct {}
func (w BaseWorker) Foo() {
// This only class BaseWorker.SomethingOverridableInChildClass()
w.SomethingOverridableInChildClass()
}
type FooWorker struct {
BaseWorker
}
func (w FooWorker) Work() {
for {
// Do interesting stuff…
w.Foo() // w.BaseWorker.Foo(), receiver is never FooWorker
}
}
Go: Another Failed Attempt
Wrong Approach:Top Down
Abstract Base Class
Concrete Implementation
Specialized Implementation
…
…
Suggested Approach: Bottom Up
Type A
Component 1
Component 2
Component 3
Component 4
Type B Type C
! Interfaces
! Promise that a type has certain
methods
Go: Grouping Types
type Greeter interface {
Greet() string
}
func main() {
p := &Person{ Name: “Mary Jane”, Age: 30 }
n := Name(“John Doe”)
greeters := []Greeters{ p, n }
…
}
Go:Things that can Greet()
func sayHello(g Greeter) {
    println(g.Greet())
}
for _, g := range greeters {
    sayHello(g)
}
Go:Things that can Greet()
! Think in terms of ability (methods)
! But note: no “base” method
implementations
Go: Interfaces
// WRONG! No methods for interfaces
func (g Greeter) SayHello() {
    println(g.Greet())
}
Go: No “base” methods
// OK. Functions that take interfaces work
func sayHello(g Greeter) {
println(g.Greet())
}
// Each type would have to make this call
func (n Name) SayHello() {
    sayHello(n) // Name is a Greeter
}
func (p Person) SayHello() {
sayHello(n) // And so is Person, through delegation to p.Name
}
Go: No “base” methods
! Think of abilities, not Is-A, Has-A
! Compose from smaller components
Go: Designing Models
! Don’t Use Exception: Use errors
Conclusions
! Don’t Expect Goroutines = Threads/
Processes
Conclusions
! Don’t Design Using Tree-style hierarchy
! Create layers of standalone functionalities
! Compose them
! Use interfaces
Conclusions
! (If you haven’t already heard) 

When In Go, Do As The Gophers Do
Conclusions
Thank You
Further reading:
! https://talks.golang.org/2014/readability.slide
! https://talks.golang.org/2014/gocon-tokyo.slide
! https://talks.golang.org/2013/bestpractices.slide
! http://blog.golang.org/errors-are-values

More Related Content

What's hot

What's hot (20)

Grafana
GrafanaGrafana
Grafana
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples
 
Fluentd v0.14 Plugin API Details
Fluentd v0.14 Plugin API DetailsFluentd v0.14 Plugin API Details
Fluentd v0.14 Plugin API Details
 
gRPC: The Story of Microservices at Square
gRPC: The Story of Microservices at SquaregRPC: The Story of Microservices at Square
gRPC: The Story of Microservices at Square
 
Architecting for the Cloud using NetflixOSS - Codemash Workshop
Architecting for the Cloud using NetflixOSS - Codemash WorkshopArchitecting for the Cloud using NetflixOSS - Codemash Workshop
Architecting for the Cloud using NetflixOSS - Codemash Workshop
 
Writing Reusable Web Components with jQuery and jQuery UI
Writing Reusable Web Components with jQuery and jQuery UIWriting Reusable Web Components with jQuery and jQuery UI
Writing Reusable Web Components with jQuery and jQuery UI
 
Postman Collection Format v2.0 (pre-draft)
Postman Collection Format v2.0 (pre-draft)Postman Collection Format v2.0 (pre-draft)
Postman Collection Format v2.0 (pre-draft)
 
API Design - 3rd Edition
API Design - 3rd EditionAPI Design - 3rd Edition
API Design - 3rd Edition
 
아파치 카프카 입문과 활용 강의자료
아파치 카프카 입문과 활용 강의자료아파치 카프카 입문과 활용 강의자료
아파치 카프카 입문과 활용 강의자료
 
Monitoring using Prometheus and Grafana
Monitoring using Prometheus and GrafanaMonitoring using Prometheus and Grafana
Monitoring using Prometheus and Grafana
 
[Golang] 以 Mobile App 工程師視角,帶你進入 Golang 的世界 (Introduction of GoLang)
[Golang] 以 Mobile App 工程師視角,帶你進入 Golang 的世界 (Introduction of GoLang) [Golang] 以 Mobile App 工程師視角,帶你進入 Golang 的世界 (Introduction of GoLang)
[Golang] 以 Mobile App 工程師視角,帶你進入 Golang 的世界 (Introduction of GoLang)
 
Reimagining Cordova: Building Cross-Platform Web Apps with Capacitor
Reimagining Cordova: Building Cross-Platform Web Apps with CapacitorReimagining Cordova: Building Cross-Platform Web Apps with Capacitor
Reimagining Cordova: Building Cross-Platform Web Apps with Capacitor
 
OpenAPI Intro (1).pdf
OpenAPI Intro (1).pdfOpenAPI Intro (1).pdf
OpenAPI Intro (1).pdf
 
Selenium Page Object Model Using Page Factory | Selenium Tutorial For Beginne...
Selenium Page Object Model Using Page Factory | Selenium Tutorial For Beginne...Selenium Page Object Model Using Page Factory | Selenium Tutorial For Beginne...
Selenium Page Object Model Using Page Factory | Selenium Tutorial For Beginne...
 
Raffi Krikorian, Twitter Timelines at Scale
Raffi Krikorian, Twitter Timelines at ScaleRaffi Krikorian, Twitter Timelines at Scale
Raffi Krikorian, Twitter Timelines at Scale
 
A GitOps Kubernetes Native CICD Solution with Argo Events, Workflows, and CD
A GitOps Kubernetes Native CICD Solution with Argo Events, Workflows, and CDA GitOps Kubernetes Native CICD Solution with Argo Events, Workflows, and CD
A GitOps Kubernetes Native CICD Solution with Argo Events, Workflows, and CD
 
Swagger
SwaggerSwagger
Swagger
 
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
 
REST-API introduction for developers
REST-API introduction for developersREST-API introduction for developers
REST-API introduction for developers
 
Modern Tools for API Testing, Debugging and Monitoring
Modern Tools for API Testing, Debugging and MonitoringModern Tools for API Testing, Debugging and Monitoring
Modern Tools for API Testing, Debugging and Monitoring
 

Viewers also liked

YAPC::Asia Tokyo 2012 Closing
YAPC::Asia Tokyo 2012 ClosingYAPC::Asia Tokyo 2012 Closing
YAPC::Asia Tokyo 2012 Closing
lestrrat
 
YAPC::Asia Tokyo 2011 Closing
YAPC::Asia Tokyo 2011 ClosingYAPC::Asia Tokyo 2011 Closing
YAPC::Asia Tokyo 2011 Closing
lestrrat
 
Ростислав Фридман: “Kubernetes как средство управления микросервисами"
Ростислав Фридман: “Kubernetes как средство управления микросервисами"Ростислав Фридман: “Kubernetes как средство управления микросервисами"
Ростислав Фридман: “Kubernetes как средство управления микросервисами"
Provectus
 

Viewers also liked (20)

小規模でもGKE - DevFest Tokyo 2016
小規模でもGKE - DevFest Tokyo 2016小規模でもGKE - DevFest Tokyo 2016
小規模でもGKE - DevFest Tokyo 2016
 
Kubernetes in 20 minutes - HDE Monthly Technical Session 24
Kubernetes in 20 minutes - HDE Monthly Technical Session 24Kubernetes in 20 minutes - HDE Monthly Technical Session 24
Kubernetes in 20 minutes - HDE Monthly Technical Session 24
 
Don't Use Reflect - Go 1.7 release party 2016
Don't Use Reflect - Go 1.7 release party 2016Don't Use Reflect - Go 1.7 release party 2016
Don't Use Reflect - Go 1.7 release party 2016
 
Opening: builderscon tokyo 2016
Opening: builderscon tokyo 2016Opening: builderscon tokyo 2016
Opening: builderscon tokyo 2016
 
いまさら聞けないselectあれこれ
いまさら聞けないselectあれこれいまさら聞けないselectあれこれ
いまさら聞けないselectあれこれ
 
Kubernetes in 30 minutes (2017/03/10)
Kubernetes in 30 minutes (2017/03/10)Kubernetes in 30 minutes (2017/03/10)
Kubernetes in 30 minutes (2017/03/10)
 
YAPC::Asia Tokyo 2012 Closing
YAPC::Asia Tokyo 2012 ClosingYAPC::Asia Tokyo 2012 Closing
YAPC::Asia Tokyo 2012 Closing
 
Yapceu 2015 yapc asia tokyo behind the scenes (w/o notes)
Yapceu 2015 yapc asia tokyo behind the scenes (w/o notes)Yapceu 2015 yapc asia tokyo behind the scenes (w/o notes)
Yapceu 2015 yapc asia tokyo behind the scenes (w/o notes)
 
On internationalcommunityrelations
On internationalcommunityrelationsOn internationalcommunityrelations
On internationalcommunityrelations
 
Kubernetesにまつわるエトセトラ(主に苦労話)
Kubernetesにまつわるエトセトラ(主に苦労話)Kubernetesにまつわるエトセトラ(主に苦労話)
Kubernetesにまつわるエトセトラ(主に苦労話)
 
Coding in the context era
Coding in the context eraCoding in the context era
Coding in the context era
 
YAPC::Asia Tokyo 2011 Closing
YAPC::Asia Tokyo 2011 ClosingYAPC::Asia Tokyo 2011 Closing
YAPC::Asia Tokyo 2011 Closing
 
Kubernetes CI/CD with Helm
Kubernetes CI/CD with HelmKubernetes CI/CD with Helm
Kubernetes CI/CD with Helm
 
RackN DevOps meetup NYC
RackN DevOps meetup NYCRackN DevOps meetup NYC
RackN DevOps meetup NYC
 
Welcome talk for Moscow Kubernetes Meetup 1
Welcome talk for Moscow Kubernetes Meetup 1Welcome talk for Moscow Kubernetes Meetup 1
Welcome talk for Moscow Kubernetes Meetup 1
 
Net core, mssql, container und kubernetes
Net core, mssql, container und kubernetesNet core, mssql, container und kubernetes
Net core, mssql, container und kubernetes
 
Mirantis Contributions to Kubernetes Ecosystem
Mirantis Contributions to Kubernetes EcosystemMirantis Contributions to Kubernetes Ecosystem
Mirantis Contributions to Kubernetes Ecosystem
 
Microservices summit talk 1/31
Microservices summit talk   1/31Microservices summit talk   1/31
Microservices summit talk 1/31
 
Keeping up with Tech
Keeping up with Tech Keeping up with Tech
Keeping up with Tech
 
Ростислав Фридман: “Kubernetes как средство управления микросервисами"
Ростислав Фридман: “Kubernetes как средство управления микросервисами"Ростислав Фридман: “Kubernetes как средство управления микросервисами"
Ростислав Фридман: “Kubernetes как средство управления микросервисами"
 

Similar to How To Think In Go

Your Library Sucks, and why you should use it.
Your Library Sucks, and why you should use it.Your Library Sucks, and why you should use it.
Your Library Sucks, and why you should use it.
Peter Higgins
 
Unix shell scripting basics
Unix shell scripting basicsUnix shell scripting basics
Unix shell scripting basics
Abhay Sapru
 
Unix Shell Scripting Basics
Unix Shell Scripting BasicsUnix Shell Scripting Basics
Unix Shell Scripting Basics
Dr.Ravi
 
Good Evils In Perl
Good Evils In PerlGood Evils In Perl
Good Evils In Perl
Kang-min Liu
 

Similar to How To Think In Go (20)

Your Library Sucks, and why you should use it.
Your Library Sucks, and why you should use it.Your Library Sucks, and why you should use it.
Your Library Sucks, and why you should use it.
 
Perl Moderno
Perl ModernoPerl Moderno
Perl Moderno
 
Geeks Anonymes - Le langage Go
Geeks Anonymes - Le langage GoGeeks Anonymes - Le langage Go
Geeks Anonymes - Le langage Go
 
Unix shell scripting basics
Unix shell scripting basicsUnix shell scripting basics
Unix shell scripting basics
 
Unix Shell Scripting Basics
Unix Shell Scripting BasicsUnix Shell Scripting Basics
Unix Shell Scripting Basics
 
The why and how of moving to PHP 5.4/5.5
The why and how of moving to PHP 5.4/5.5The why and how of moving to PHP 5.4/5.5
The why and how of moving to PHP 5.4/5.5
 
OSCON2014 : Quick Introduction to System Tools Programming with Go
OSCON2014 : Quick Introduction to System Tools Programming with GoOSCON2014 : Quick Introduction to System Tools Programming with Go
OSCON2014 : Quick Introduction to System Tools Programming with Go
 
GoCracow #5 Bartlomiej klimczak - GoBDD
GoCracow #5 Bartlomiej klimczak - GoBDDGoCracow #5 Bartlomiej klimczak - GoBDD
GoCracow #5 Bartlomiej klimczak - GoBDD
 
Good Evils In Perl
Good Evils In PerlGood Evils In Perl
Good Evils In Perl
 
2013-06-15 - Software Craftsmanship mit JavaScript
2013-06-15 - Software Craftsmanship mit JavaScript2013-06-15 - Software Craftsmanship mit JavaScript
2013-06-15 - Software Craftsmanship mit JavaScript
 
2013-06-24 - Software Craftsmanship with JavaScript
2013-06-24 - Software Craftsmanship with JavaScript2013-06-24 - Software Craftsmanship with JavaScript
2013-06-24 - Software Craftsmanship with JavaScript
 
golang_getting_started.pptx
golang_getting_started.pptxgolang_getting_started.pptx
golang_getting_started.pptx
 
ppt7
ppt7ppt7
ppt7
 
ppt2
ppt2ppt2
ppt2
 
name name2 n
name name2 nname name2 n
name name2 n
 
name name2 n2
name name2 n2name name2 n2
name name2 n2
 
test ppt
test ppttest ppt
test ppt
 
name name2 n
name name2 nname name2 n
name name2 n
 
ppt21
ppt21ppt21
ppt21
 
name name2 n
name name2 nname name2 n
name name2 n
 

More from lestrrat

Running JPA (YAPC::NA 2011)
Running JPA (YAPC::NA 2011)Running JPA (YAPC::NA 2011)
Running JPA (YAPC::NA 2011)
lestrrat
 
CPAN Gems From The Far East
CPAN Gems From The Far EastCPAN Gems From The Far East
CPAN Gems From The Far East
lestrrat
 
Why Don't You Do Your Test - Fukuoka Perl Workshop #18
Why Don't You Do Your Test - Fukuoka Perl Workshop #18Why Don't You Do Your Test - Fukuoka Perl Workshop #18
Why Don't You Do Your Test - Fukuoka Perl Workshop #18
lestrrat
 
JPA 活動報告 2010/09 Shibuya.pm #14
JPA 活動報告 2010/09 Shibuya.pm #14JPA 活動報告 2010/09 Shibuya.pm #14
JPA 活動報告 2010/09 Shibuya.pm #14
lestrrat
 
Perl 非同期プログラミング
Perl 非同期プログラミングPerl 非同期プログラミング
Perl 非同期プログラミング
lestrrat
 
Perlの現在と未来 2010
Perlの現在と未来 2010Perlの現在と未来 2010
Perlの現在と未来 2010
lestrrat
 

More from lestrrat (19)

Future of Tech "Conferences"
Future of Tech "Conferences"Future of Tech "Conferences"
Future of Tech "Conferences"
 
ONIの世界 - ONIcon 2019 Winter
ONIの世界 - ONIcon 2019 WinterONIの世界 - ONIcon 2019 Winter
ONIの世界 - ONIcon 2019 Winter
 
Slicing, Dicing, And Linting OpenAPI
Slicing, Dicing, And Linting OpenAPISlicing, Dicing, And Linting OpenAPI
Slicing, Dicing, And Linting OpenAPI
 
Oxygen Not Includedをやるべき4つの理由
Oxygen Not Includedをやるべき4つの理由Oxygen Not Includedをやるべき4つの理由
Oxygen Not Includedをやるべき4つの理由
 
Rejectcon 2018
Rejectcon 2018Rejectcon 2018
Rejectcon 2018
 
Builderscon tokyo 2018 speaker dinner
Builderscon tokyo 2018 speaker dinnerBuilderscon tokyo 2018 speaker dinner
Builderscon tokyo 2018 speaker dinner
 
GoらしいAPIを求める旅路 (Go Conference 2018 Spring)
GoらしいAPIを求める旅路 (Go Conference 2018 Spring)GoらしいAPIを求める旅路 (Go Conference 2018 Spring)
GoらしいAPIを求める旅路 (Go Conference 2018 Spring)
 
Google container builderと友だちになるまで
Google container builderと友だちになるまでGoogle container builderと友だちになるまで
Google container builderと友だちになるまで
 
筋肉によるGoコードジェネレーション
筋肉によるGoコードジェネレーション筋肉によるGoコードジェネレーション
筋肉によるGoコードジェネレーション
 
iosdc 2017
iosdc 2017iosdc 2017
iosdc 2017
 
シュラスコの食べ方 超入門
シュラスコの食べ方 超入門シュラスコの食べ方 超入門
シュラスコの食べ方 超入門
 
OSSの敵になるのもいいじゃない
OSSの敵になるのもいいじゃないOSSの敵になるのもいいじゃない
OSSの敵になるのもいいじゃない
 
Running JPA (YAPC::NA 2011)
Running JPA (YAPC::NA 2011)Running JPA (YAPC::NA 2011)
Running JPA (YAPC::NA 2011)
 
CPAN Gems From The Far East
CPAN Gems From The Far EastCPAN Gems From The Far East
CPAN Gems From The Far East
 
Why Don't You Do Your Test - Fukuoka Perl Workshop #18
Why Don't You Do Your Test - Fukuoka Perl Workshop #18Why Don't You Do Your Test - Fukuoka Perl Workshop #18
Why Don't You Do Your Test - Fukuoka Perl Workshop #18
 
Perlで任意精度計算
Perlで任意精度計算Perlで任意精度計算
Perlで任意精度計算
 
JPA 活動報告 2010/09 Shibuya.pm #14
JPA 活動報告 2010/09 Shibuya.pm #14JPA 活動報告 2010/09 Shibuya.pm #14
JPA 活動報告 2010/09 Shibuya.pm #14
 
Perl 非同期プログラミング
Perl 非同期プログラミングPerl 非同期プログラミング
Perl 非同期プログラミング
 
Perlの現在と未来 2010
Perlの現在と未来 2010Perlの現在と未来 2010
Perlの現在と未来 2010
 

Recently uploaded

Call Girls In Ashram Chowk Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Ashram Chowk Delhi 💯Call Us 🔝8264348440🔝Call Girls In Ashram Chowk Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Ashram Chowk Delhi 💯Call Us 🔝8264348440🔝
soniya singh
 
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
soniya singh
 
Call Girls Service Chandigarh Lucky ❤️ 7710465962 Independent Call Girls In C...
Call Girls Service Chandigarh Lucky ❤️ 7710465962 Independent Call Girls In C...Call Girls Service Chandigarh Lucky ❤️ 7710465962 Independent Call Girls In C...
Call Girls Service Chandigarh Lucky ❤️ 7710465962 Independent Call Girls In C...
Sheetaleventcompany
 
valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
Call Girls In Delhi Whatsup 9873940964 Enjoy Unlimited Pleasure
 
Dwarka Sector 26 Call Girls | Delhi | 9999965857 🫦 Vanshika Verma More Our Se...
Dwarka Sector 26 Call Girls | Delhi | 9999965857 🫦 Vanshika Verma More Our Se...Dwarka Sector 26 Call Girls | Delhi | 9999965857 🫦 Vanshika Verma More Our Se...
Dwarka Sector 26 Call Girls | Delhi | 9999965857 🫦 Vanshika Verma More Our Se...
Call Girls In Delhi Whatsup 9873940964 Enjoy Unlimited Pleasure
 

Recently uploaded (20)

All Time Service Available Call Girls Mg Road 👌 ⏭️ 6378878445
All Time Service Available Call Girls Mg Road 👌 ⏭️ 6378878445All Time Service Available Call Girls Mg Road 👌 ⏭️ 6378878445
All Time Service Available Call Girls Mg Road 👌 ⏭️ 6378878445
 
VVIP Pune Call Girls Sinhagad WhatSapp Number 8005736733 With Elite Staff And...
VVIP Pune Call Girls Sinhagad WhatSapp Number 8005736733 With Elite Staff And...VVIP Pune Call Girls Sinhagad WhatSapp Number 8005736733 With Elite Staff And...
VVIP Pune Call Girls Sinhagad WhatSapp Number 8005736733 With Elite Staff And...
 
Shikrapur - Call Girls in Pune Neha 8005736733 | 100% Gennuine High Class Ind...
Shikrapur - Call Girls in Pune Neha 8005736733 | 100% Gennuine High Class Ind...Shikrapur - Call Girls in Pune Neha 8005736733 | 100% Gennuine High Class Ind...
Shikrapur - Call Girls in Pune Neha 8005736733 | 100% Gennuine High Class Ind...
 
VIP Model Call Girls NIBM ( Pune ) Call ON 8005736733 Starting From 5K to 25K...
VIP Model Call Girls NIBM ( Pune ) Call ON 8005736733 Starting From 5K to 25K...VIP Model Call Girls NIBM ( Pune ) Call ON 8005736733 Starting From 5K to 25K...
VIP Model Call Girls NIBM ( Pune ) Call ON 8005736733 Starting From 5K to 25K...
 
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
 
VIP Model Call Girls Hadapsar ( Pune ) Call ON 9905417584 Starting High Prof...
VIP Model Call Girls Hadapsar ( Pune ) Call ON 9905417584 Starting  High Prof...VIP Model Call Girls Hadapsar ( Pune ) Call ON 9905417584 Starting  High Prof...
VIP Model Call Girls Hadapsar ( Pune ) Call ON 9905417584 Starting High Prof...
 
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark Web
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark WebGDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark Web
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark Web
 
Call Girls In Ashram Chowk Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Ashram Chowk Delhi 💯Call Us 🔝8264348440🔝Call Girls In Ashram Chowk Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Ashram Chowk Delhi 💯Call Us 🔝8264348440🔝
 
On Starlink, presented by Geoff Huston at NZNOG 2024
On Starlink, presented by Geoff Huston at NZNOG 2024On Starlink, presented by Geoff Huston at NZNOG 2024
On Starlink, presented by Geoff Huston at NZNOG 2024
 
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
 
(+971568250507 ))# Young Call Girls in Ajman By Pakistani Call Girls in ...
(+971568250507  ))#  Young Call Girls  in Ajman  By Pakistani Call Girls  in ...(+971568250507  ))#  Young Call Girls  in Ajman  By Pakistani Call Girls  in ...
(+971568250507 ))# Young Call Girls in Ajman By Pakistani Call Girls in ...
 
Pune Airport ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready...
Pune Airport ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready...Pune Airport ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready...
Pune Airport ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready...
 
Call Now ☎ 8264348440 !! Call Girls in Rani Bagh Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Rani Bagh Escort Service Delhi N.C.R.Call Now ☎ 8264348440 !! Call Girls in Rani Bagh Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Rani Bagh Escort Service Delhi N.C.R.
 
Dubai=Desi Dubai Call Girls O525547819 Outdoor Call Girls Dubai
Dubai=Desi Dubai Call Girls O525547819 Outdoor Call Girls DubaiDubai=Desi Dubai Call Girls O525547819 Outdoor Call Girls Dubai
Dubai=Desi Dubai Call Girls O525547819 Outdoor Call Girls Dubai
 
Moving Beyond Twitter/X and Facebook - Social Media for local news providers
Moving Beyond Twitter/X and Facebook - Social Media for local news providersMoving Beyond Twitter/X and Facebook - Social Media for local news providers
Moving Beyond Twitter/X and Facebook - Social Media for local news providers
 
Call Girls Service Chandigarh Lucky ❤️ 7710465962 Independent Call Girls In C...
Call Girls Service Chandigarh Lucky ❤️ 7710465962 Independent Call Girls In C...Call Girls Service Chandigarh Lucky ❤️ 7710465962 Independent Call Girls In C...
Call Girls Service Chandigarh Lucky ❤️ 7710465962 Independent Call Girls In C...
 
WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)
WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)
WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)
 
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...
 
valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
 
Dwarka Sector 26 Call Girls | Delhi | 9999965857 🫦 Vanshika Verma More Our Se...
Dwarka Sector 26 Call Girls | Delhi | 9999965857 🫦 Vanshika Verma More Our Se...Dwarka Sector 26 Call Girls | Delhi | 9999965857 🫦 Vanshika Verma More Our Se...
Dwarka Sector 26 Call Girls | Delhi | 9999965857 🫦 Vanshika Verma More Our Se...
 

How To Think In Go

  • 1. How To Think In Go or, let me tell you about all the ways I screwed up
  • 2.
  • 3.
  • 4.
  • 5.
  • 8. “Oh look, panic() and rescue()! I can probably use it like lightweight exceptions!” Misconception
  • 9.
  • 10. ! panic: unrecoverable errors ! error: recoverable errors panic / error
  • 11. sub foo { eval { might_die(); }; if ($@) { # handle $@ } important_task(); } Perl: Exceptions
  • 12. func main() { defer func() { if err := recover(); err != nil { // handle err } }() mightPanic() importantTask() // Never reached if mightPanic() panics } A bad port
  • 13. func mightPanic() { defer func() { if err := recover(); err != nil { // handle err } }() panic(“BOO!”) } func main() { mightPanic() importantTask() } Attempt #2
  • 14. func main() { if err := tryit(mightPanic); err != nil { fmt.Printf(“Found error: %sn”, err) } importantTask() } func mightPanic() { panic(“BOO!”) } Attempt #3
  • 15. func tryit(code func()) (err error) {     defer func() {         if e := recover(); e != nil {             var ok bool             if err, ok = e.(error); !ok {                 err = fmt.Errorf("%s", e)             }         }     }()     code()     return err } Attempt #3
  • 16.
  • 17. “Why don’t I just use plain errors to begin with?” Go Way
  • 18. func mightError() error {      if errorCase {           return errors.New(“error case 1”)      }      if err := someOtherThingMightError(); err != nil {           // propagate error           return err      }      return nil } Use errors!
  • 19. func main() {      if err := mightError(); err != nil {          // handle it      }      importantTask() } Use errors!
  • 20. ! Do not dream about exceptions ! Do stick with errors Use errors!
  • 22. “Go’s makes concurrency so easy, we can just port our multi-process code in an instant!” Misconception
  • 23.
  • 24. ! PIDs to identify processes ! Processes can be signaled ! Processes can notify termination Processes
  • 25. ! No pid to identify goroutines ! No signals to communicate ! Goroutines don’t notify on exit Goroutine
  • 26. sub sub main {      my $pid = fork();      if (! defined $pid) { die “Failed to fork: $!” }      if (! $pid) { while(1) { do_stuff() } }      $SIG{CHLD} = sub {            my $pid = wait;            print “reaped $pidn”;      };      sleep 5;      kill TERM => $pid;      while (kill 0 => $pid) { sleep 1 } } Perl: Processes
  • 27. func main() { // Won’t work     go func() { for { doStuff() } } } Go: A simple goroutine
  • 28. func main() {     exitCh := make(chan struct{}) go func() { defer func() { close(exitCh) }() // close upon termination for { doStuff() } } <-exitCh // Wait for something to happen } Go: Detect termination
  • 29. func main() {     exitCh := make(chan struct{}) incomingCh := make(chan struct{}) go func() { defer func() { close(exitCh) }() // close upon termination for { select { case <-incomingCh: // Got termination request return } doStuff() } } Go:Accept Termination Request
  • 30. // Send request to terminate loop time.AfterFunc(5 * time.Second, func() { incomingCh <-struct{}{} }) <-exitCh // Wait for something to happen } Go:Accept Termination Request
  • 31. ! Explicit coordination required ! No goroutine specific storage Goroutine
  • 32. ! You must explicitly bail out for infinite loops in goroutines One more thing:
  • 33. ! Still, goroutines are worth it ! Channels can do much more Too much hassle?
  • 35. “Structs and methods will allow us to make our Object-oriented code easy to port” Misconception
  • 36.
  • 38. package Worker::Base; # snip sub foo { # do stuff.. shift->something_overridable_in_child_class(); } sub something_overridable_in_child_class { … } Perl: Interaction Between Parent/Child
  • 39. package Worker::Foo; # snip use parent qw(Worker::Base); sub something_overridable_in_child_class { … } sub work { my $self = shift; while (1) { # do stuff… $self->foo(); # Doesn’t translate very well into Go } } Perl: Interaction Between Parent/Child
  • 40.
  • 41. ! No. Just No. ! Embedded structs + Automatic Delegation Go: No Inheritance
  • 42. type Name string func (n Name) Greet() string { return fmt.Sprintf(“Hello, my name is %s”, n) } Go: Name
  • 43. n := Name(“Daisuke Maki”) println(n.Greet()) // “Hello, my name is Daisuke Maki” Go: Name
  • 44. type Person struct { Name // Embedded struct Age uint // A regular field } Go: Person
  • 45. p := &Person{ Name: Name(“Daisuke Maki”), Age: 38 } println(p.Greet()) // “Hello, my name is Daisuke Maki” Go: Automatic Delegation
  • 46. p.Greet() // → p.Name.Greet() // The receiver is p.Name, not p. Go: Automatic Delegation
  • 47. func (p Person) Greet() string { return fmt.Sprintf( “%s. I’m %d years old”, p.Super.Greet(), // Pseudo-code. Doesn’t work p.Age, ) } Go: Customizing Person.Greet()
  • 48. type BaseWorker struct {} func (w BaseWorker) Foo() { // This only class BaseWorker.SomethingOverridableInChildClass() w.SomethingOverridableInChildClass() } type FooWorker struct { BaseWorker } func (w FooWorker) Work() { for { // Do interesting stuff… w.Foo() // w.BaseWorker.Foo(), receiver is never FooWorker } } Go: Another Failed Attempt
  • 49. Wrong Approach:Top Down Abstract Base Class Concrete Implementation Specialized Implementation … …
  • 50. Suggested Approach: Bottom Up Type A Component 1 Component 2 Component 3 Component 4 Type B Type C
  • 51. ! Interfaces ! Promise that a type has certain methods Go: Grouping Types
  • 52. type Greeter interface { Greet() string } func main() { p := &Person{ Name: “Mary Jane”, Age: 30 } n := Name(“John Doe”) greeters := []Greeters{ p, n } … } Go:Things that can Greet()
  • 53. func sayHello(g Greeter) {     println(g.Greet()) } for _, g := range greeters {     sayHello(g) } Go:Things that can Greet()
  • 54. ! Think in terms of ability (methods) ! But note: no “base” method implementations Go: Interfaces
  • 55. // WRONG! No methods for interfaces func (g Greeter) SayHello() {     println(g.Greet()) } Go: No “base” methods
  • 56. // OK. Functions that take interfaces work func sayHello(g Greeter) { println(g.Greet()) } // Each type would have to make this call func (n Name) SayHello() {     sayHello(n) // Name is a Greeter } func (p Person) SayHello() { sayHello(n) // And so is Person, through delegation to p.Name } Go: No “base” methods
  • 57. ! Think of abilities, not Is-A, Has-A ! Compose from smaller components Go: Designing Models
  • 58. ! Don’t Use Exception: Use errors Conclusions
  • 59. ! Don’t Expect Goroutines = Threads/ Processes Conclusions
  • 60. ! Don’t Design Using Tree-style hierarchy ! Create layers of standalone functionalities ! Compose them ! Use interfaces Conclusions
  • 61. ! (If you haven’t already heard) 
 When In Go, Do As The Gophers Do Conclusions
  • 62. Thank You Further reading: ! https://talks.golang.org/2014/readability.slide ! https://talks.golang.org/2014/gocon-tokyo.slide ! https://talks.golang.org/2013/bestpractices.slide ! http://blog.golang.org/errors-are-values