SlideShare a Scribd company logo
Go for Object 

Oriented Programmers
!
or
!
Object Oriented Programming 

Without Objects
• Author of Hugo, Cobra,
Viper & More
• Chief Developer
Advocate for MongoDB
• Gopher
@spf13
— txxxxd
“Most of the appeal for me is not
the features that Go has, but
rather the features that have
been intentionally left out.”
— Rob Pike
“Why would you have a
language that is not
theoretically exciting?
Because it’s very useful.”
“Objects” 

in Go
Does Go have Objects?
• Go lacks Classes
• Go lacks “Objects”
What is an
Object?
– Steve Francia
“An object is an
abstract data type that
has state (data) and
behavior (code).”
type Rect struct {
width int
height int
}
Type Declaration (Struct)
func (r *Rect) Area() int {
return r.width * r.height
}
Declaring a Method
func main() {
r := Rect{width: 10, height: 5}
fmt.Println("area: ", r.Area())
}
In Action
type Rects []Rect
Type Declaration (Slice)
func (rs Rects) Area() int {
var a int
for _, r := range rs {
a += r.Area()
}
return a
}
Declaring a Method
func main() {
r := Rect{width: 10, height: 5}
x := Rect{width: 7, height:10}
rs := Rects{r, x}
fmt.Println("r's area: ", r.Area())
fmt.Println("x's area: ", x.Area())
fmt.Println("total area: ", rs.Area())
}
In Action
http://play.golang.org/p/G1OWXPGvc3
type Foo func() int
Type Declaration (Func)
func (f Foo) Add(x int) int {
return f() + x
}
Declaring a Method
func main() {
var x Foo
!
x = func() int { return 1 }
!
fmt.Println(x())
fmt.Println(x.Add(3))
}
In Action
http://play.golang.org/p/YGrdCG3SlI
Go Has
“Objects”
“Object Oriented”
Go
– Wikipedia
A language is usually considered object-based
if it includes the basic capabilities for an
object: identity, properties, and attributes.


A language is considered object-oriented if it
is object-based and also has the capability of
polymorphism and inheritance.
Go is Object Based.
!
Is it OO?
Inheritance
• Provides reuse of objects
• Classes are created in hierarchies
• Inheritance lets the structure and
methods in one class pass down the
hierarchy
Go’s approach
• Go explicitly avoided inheritance
• Go strictly follows the composition over
inheritance principle
• Composition through embedded types
Composition
• Provides reuse of Objects
• One object is declared by including other
objects
• Composition lets the structure and methods
in one class be pulled into another
– Steve Francia
Inheritance passes “knowledge” down
!
Composition pulls “knowledge” up
type Person struct {
Name string
Address
}
!
!
type Address struct {
Number string
Street string
City string
State string
Zip string
}
Embedding Types
Inner Type
func (a *Address) String() string {
return a.Number+" "+a.Street+"n"+

a.City+", "+a.State+" "+a.Zip+"n"
}
Declaring a Method
func main() {
p := Person{
Name: "Steve",
Address: Address{
Number: "13",
Street: "Main",
City: "Gotham",
State: "NY",
Zip: "01313",
},
}
}
Declare using Composite Literal
func main() {
p := Person{
Name: "Steve",
Address: Address{
Number: "13",
Street: "Main",
City: "Gotham",
State: "NY",
Zip: "01313",
},
}
fmt.Println(p.String())
In Action
http://play.golang.org/p/9beVY9jNlW
Promotion
• Promotion looks to see if a single inner type can
satisify the request and “promotes” it
• Embedded fields & methods are “promoted”
• Promotion only occurs during usage, not declaration
• Promoted methods are considered for interface
adherance
func (a *Address) String() string {
return a.Number+" "+a.Street+"n"+

a.City+", "+a.State+" "+a.Zip+"n"
}
!
func (p *Person) String() string {
return p.Name + "n" + p.Address.String()
}
Not Overloading
func main() {
p := Person{
Name: "Steve",
Address: Address{
Number: "13",
Street: "Main",
City: "Gotham",
State: "NY",
Zip: "01313",
},
}
!
fmt.Println(p.String())
fmt.Println(p.Address.String())
}
Both Methods Available
http://play.golang.org/p/Aui0nGa5Xi
func isValidAddress(a *Address) bool {
return a.Street != ""
}
!
func main() {
p := Person{ Name: "Steve", Address: Address{ Number: "13", Street:
"Main", City: "Gotham", State: "NY", Zip: "01313"}}
!
fmt.Println(isValidAddress(p)) 

// cannot use p (type Person) as type Address 

// in argument to isValidAddress
fmt.Println(isValidAddress(p.Address))
}
Types Remain Distinct
http://play.golang.org/p/KYjXZxNBcQ
Promotion is
NOT Subtyping
Polymorphism
• “The provision of a single interface to
entities of different types”
• Typically implmented via Generics,
Overloading and/or Subtyping
Go’s approach
• Go explicitly avoided subtyping &
overloading
• Go does not provide Generics (yet)
• Go’s interface provide polymorphic
capabilities
Interfaces
• A list of required methods
• Structural vs Nominal typing
• ‘‘If something can do this, then it can be
used here”
• Convention is call it a Something-er
type Shaper interface {
Area() int
}
Interface Declaration
func Describe(s Shaper) {
fmt.Println("Area is:", s.Area())
}
Using Interface as Param Type
func main() {
r := &Rect{width: 10, height: 5}
x := &Rect{width: 7, height: 10}
rs := &Rects{r, x}
Describe(r)
Describe(x)
Describe(rs)
}
In Action
http://play.golang.org/p/WL77LihUwi
–James Gosling (creator of Java)
“If you could do Java over again, what would you
change?” “I’d leave out classes,” he replied. After the
laughter died down, he explained that the real
problem wasn’t classes per se, but rather
implementation inheritance (the extends
relationship). Interface inheritance (the implements
relationship) is preferable. You should avoid
implementation inheritance whenever possible.
Go Interfaces are
based on
implementation,
not declaration
The Power of
Interfaces
type Reader interface {
Read(p []byte) (n int, err error)
}
io.Reader
io.Reader
• Interface
• Read reads up to len(p) bytes into p
• Returns the # of bytes read & any error
• Does not dictate how Read() is implemented
• Used by os.File, bytes.Buffer, net.Conn,
http.Request.Body, loads more
type Writer interface {
Write(p []byte) (n int, err error)
}
io.Writer
io.Writer
• Interface
• Write writes up to len(p) bytes into p
• Returns the # of bytes written & any error
• Does not dictate how Write() is implemented
• Used by os.File, bytes.Buffer, net.Conn,
http.Response.Body, loads more
func MarshalGzippedJSON(r io.Reader, 

v interface{}) error {
raw, err := gzip.NewReader(r)
if err != nil {
return err
}
return json.NewDecoder(raw).Decode(&v)
}
io.Reader in Action
f, err := os.Open("myfile.json.gz")
if err != nil {
log.Fatalln(err)
}
defer f.Close()
m = make(map[string]interface{})
MarshalGzippedJSON(f, &m)
Reading a json.gz file
Practical Interoperability
• Gzip.NewReader(io.Reader)
• Works on files, http requests, byte buffers,
network connections, …anything you create
• Nothing special needed in gzip to be able to
do this… Simply call Read(n) and leave the
abstracting to the implementor
func main() {
resp, err := http.Get("...")
if err != nil {
log.Fatalln(err)
}
defer resp.Body.Close()
out, err := os.Create("filename.ext")
if err != nil {
log.Fatalln(err)
}
defer out.Close()
io.Copy(out, resp.Body) // out io.Writer, resp.Body io.Reader
}
Pipe http response to file
Go
— Steve Jobs
Simple can be harder than
complex: You have to work hard
to get your thinking clean to
make it simple. But it's worth it
in the end because once you get
there, you can move mountains.
Go is simple,
pratical &
wonderful
Go build
something
great
Thank You

More Related Content

PDF
7 Common Mistakes in Go (2015)
PDF
Java 8, Streams & Collectors, patterns, performances and parallelization
PDF
Action Jackson! Effective JSON processing in Spring Boot Applications
PDF
Python testing using mock and pytest
PDF
Introdução a estruturas de dados em python
PDF
Node js (runtime environment + js library) platform
PPSX
Algoritmos de busca
PDF
PostgreSQL: O melhor banco de dados Universo
7 Common Mistakes in Go (2015)
Java 8, Streams & Collectors, patterns, performances and parallelization
Action Jackson! Effective JSON processing in Spring Boot Applications
Python testing using mock and pytest
Introdução a estruturas de dados em python
Node js (runtime environment + js library) platform
Algoritmos de busca
PostgreSQL: O melhor banco de dados Universo

Viewers also liked (20)

PDF
Painless Data Storage with MongoDB & Go
PDF
The Future of the Operating System - Keynote LinuxCon 2015
PDF
Getting Started with Go
PDF
7 Common mistakes in Go and when to avoid them
PDF
What every successful open source project needs
PDF
Building Awesome CLI apps in Go
PDF
Build your first MongoDB App in Ruby @ StrangeLoop 2013
KEY
Big data for the rest of us
PDF
MongoDB, Hadoop and humongous data - MongoSV 2012
KEY
OSCON 2012 MongoDB Tutorial
PPT
20. Object-Oriented Programming Fundamental Principles
PDF
A Recovering Java Developer Learns to Go
PPTX
Object-oriented programming
PDF
Demystifying Object-Oriented Programming - PHP UK Conference 2017
PPTX
Mongo db - How we use Go and MongoDB by Sam Helman
PPT
Concepts In Object Oriented Programming Languages
PPT
Object Oriented Concept
 
PPTX
Need of object oriented programming
PDF
Architecting for the Cloud using NetflixOSS - Codemash Workshop
PPTX
oops concept in java | object oriented programming in java
Painless Data Storage with MongoDB & Go
The Future of the Operating System - Keynote LinuxCon 2015
Getting Started with Go
7 Common mistakes in Go and when to avoid them
What every successful open source project needs
Building Awesome CLI apps in Go
Build your first MongoDB App in Ruby @ StrangeLoop 2013
Big data for the rest of us
MongoDB, Hadoop and humongous data - MongoSV 2012
OSCON 2012 MongoDB Tutorial
20. Object-Oriented Programming Fundamental Principles
A Recovering Java Developer Learns to Go
Object-oriented programming
Demystifying Object-Oriented Programming - PHP UK Conference 2017
Mongo db - How we use Go and MongoDB by Sam Helman
Concepts In Object Oriented Programming Languages
Object Oriented Concept
 
Need of object oriented programming
Architecting for the Cloud using NetflixOSS - Codemash Workshop
oops concept in java | object oriented programming in java
Ad

Similar to Go for Object Oriented Programmers or Object Oriented Programming without Objects (20)

PPTX
Introduction to Go
PDF
sbt, history of JSON libraries, microservices, and schema evolution (Tokyo ver)
PDF
Json the-x-in-ajax1588
PDF
Go Workshop Day 1
PPTX
C# 6 and 7 and Futures 20180607
PPSX
Tuga IT 2017 - What's new in C# 7
PDF
Kotlin Austin Droids April 14 2016
PPT
Javascript
PDF
Denis Lebedev, Swift
PPT
json.ppt download for free for college project
PDF
EmberConf 2021 - Crossfile Codemodding with Joshua Lawrence
PDF
Scala the language matters
ODP
Dynamic Python
PDF
Json at work overview and ecosystem-v2.0
PDF
型ヒントについて考えよう!
PPT
2007 09 10 Fzi Training Groovy Grails V Ws
PPT
The Kotlin Programming Language
PPT
devLink - What's New in C# 4?
PPTX
Golang slidesaudrey
Introduction to Go
sbt, history of JSON libraries, microservices, and schema evolution (Tokyo ver)
Json the-x-in-ajax1588
Go Workshop Day 1
C# 6 and 7 and Futures 20180607
Tuga IT 2017 - What's new in C# 7
Kotlin Austin Droids April 14 2016
Javascript
Denis Lebedev, Swift
json.ppt download for free for college project
EmberConf 2021 - Crossfile Codemodding with Joshua Lawrence
Scala the language matters
Dynamic Python
Json at work overview and ecosystem-v2.0
型ヒントについて考えよう!
2007 09 10 Fzi Training Groovy Grails V Ws
The Kotlin Programming Language
devLink - What's New in C# 4?
Golang slidesaudrey
Ad

More from Steven Francia (19)

PDF
State of the Gopher Nation - Golang - August 2017
PDF
Modern Database Systems (for Genealogy)
PPTX
Introduction to MongoDB and Hadoop
PPTX
Future of data
KEY
Replication, Durability, and Disaster Recovery
KEY
Multi Data Center Strategies
KEY
NoSQL databases and managing big data
KEY
MongoDB, Hadoop and Humongous Data
KEY
MongoDB and hadoop
KEY
MongoDB for Genealogy
KEY
Hybrid MongoDB and RDBMS Applications
KEY
Building your first application w/mongoDB MongoSV2011
KEY
MongoDB, E-commerce and Transactions
KEY
MongoDB, PHP and the cloud - php cloud summit 2011
KEY
MongoDB and PHP ZendCon 2011
KEY
KEY
Blending MongoDB and RDBMS for ecommerce
KEY
Augmenting RDBMS with MongoDB for ecommerce
KEY
MongoDB and Ecommerce : A perfect combination
State of the Gopher Nation - Golang - August 2017
Modern Database Systems (for Genealogy)
Introduction to MongoDB and Hadoop
Future of data
Replication, Durability, and Disaster Recovery
Multi Data Center Strategies
NoSQL databases and managing big data
MongoDB, Hadoop and Humongous Data
MongoDB and hadoop
MongoDB for Genealogy
Hybrid MongoDB and RDBMS Applications
Building your first application w/mongoDB MongoSV2011
MongoDB, E-commerce and Transactions
MongoDB, PHP and the cloud - php cloud summit 2011
MongoDB and PHP ZendCon 2011
Blending MongoDB and RDBMS for ecommerce
Augmenting RDBMS with MongoDB for ecommerce
MongoDB and Ecommerce : A perfect combination

Recently uploaded (20)

PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPTX
MYSQL Presentation for SQL database connectivity
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPT
Teaching material agriculture food technology
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
Big Data Technologies - Introduction.pptx
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Encapsulation theory and applications.pdf
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
“AI and Expert System Decision Support & Business Intelligence Systems”
Understanding_Digital_Forensics_Presentation.pptx
Review of recent advances in non-invasive hemoglobin estimation
Mobile App Security Testing_ A Comprehensive Guide.pdf
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Encapsulation_ Review paper, used for researhc scholars
MIND Revenue Release Quarter 2 2025 Press Release
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Reach Out and Touch Someone: Haptics and Empathic Computing
MYSQL Presentation for SQL database connectivity
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Teaching material agriculture food technology
Building Integrated photovoltaic BIPV_UPV.pdf
Big Data Technologies - Introduction.pptx
The Rise and Fall of 3GPP – Time for a Sabbatical?
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Spectral efficient network and resource selection model in 5G networks
Encapsulation theory and applications.pdf

Go for Object Oriented Programmers or Object Oriented Programming without Objects

  • 1. Go for Object 
 Oriented Programmers ! or ! Object Oriented Programming 
 Without Objects
  • 2. • Author of Hugo, Cobra, Viper & More • Chief Developer Advocate for MongoDB • Gopher @spf13
  • 3. — txxxxd “Most of the appeal for me is not the features that Go has, but rather the features that have been intentionally left out.”
  • 4. — Rob Pike “Why would you have a language that is not theoretically exciting? Because it’s very useful.”
  • 6. Does Go have Objects? • Go lacks Classes • Go lacks “Objects”
  • 8. – Steve Francia “An object is an abstract data type that has state (data) and behavior (code).”
  • 9. type Rect struct { width int height int } Type Declaration (Struct)
  • 10. func (r *Rect) Area() int { return r.width * r.height } Declaring a Method
  • 11. func main() { r := Rect{width: 10, height: 5} fmt.Println("area: ", r.Area()) } In Action
  • 12. type Rects []Rect Type Declaration (Slice)
  • 13. func (rs Rects) Area() int { var a int for _, r := range rs { a += r.Area() } return a } Declaring a Method
  • 14. func main() { r := Rect{width: 10, height: 5} x := Rect{width: 7, height:10} rs := Rects{r, x} fmt.Println("r's area: ", r.Area()) fmt.Println("x's area: ", x.Area()) fmt.Println("total area: ", rs.Area()) } In Action http://play.golang.org/p/G1OWXPGvc3
  • 15. type Foo func() int Type Declaration (Func)
  • 16. func (f Foo) Add(x int) int { return f() + x } Declaring a Method
  • 17. func main() { var x Foo ! x = func() int { return 1 } ! fmt.Println(x()) fmt.Println(x.Add(3)) } In Action http://play.golang.org/p/YGrdCG3SlI
  • 20. – Wikipedia A language is usually considered object-based if it includes the basic capabilities for an object: identity, properties, and attributes. 
 A language is considered object-oriented if it is object-based and also has the capability of polymorphism and inheritance.
  • 21. Go is Object Based. ! Is it OO?
  • 22. Inheritance • Provides reuse of objects • Classes are created in hierarchies • Inheritance lets the structure and methods in one class pass down the hierarchy
  • 23. Go’s approach • Go explicitly avoided inheritance • Go strictly follows the composition over inheritance principle • Composition through embedded types
  • 24. Composition • Provides reuse of Objects • One object is declared by including other objects • Composition lets the structure and methods in one class be pulled into another
  • 25. – Steve Francia Inheritance passes “knowledge” down ! Composition pulls “knowledge” up
  • 26. type Person struct { Name string Address } ! ! type Address struct { Number string Street string City string State string Zip string } Embedding Types Inner Type
  • 27. func (a *Address) String() string { return a.Number+" "+a.Street+"n"+
 a.City+", "+a.State+" "+a.Zip+"n" } Declaring a Method
  • 28. func main() { p := Person{ Name: "Steve", Address: Address{ Number: "13", Street: "Main", City: "Gotham", State: "NY", Zip: "01313", }, } } Declare using Composite Literal
  • 29. func main() { p := Person{ Name: "Steve", Address: Address{ Number: "13", Street: "Main", City: "Gotham", State: "NY", Zip: "01313", }, } fmt.Println(p.String()) In Action http://play.golang.org/p/9beVY9jNlW
  • 30. Promotion • Promotion looks to see if a single inner type can satisify the request and “promotes” it • Embedded fields & methods are “promoted” • Promotion only occurs during usage, not declaration • Promoted methods are considered for interface adherance
  • 31. func (a *Address) String() string { return a.Number+" "+a.Street+"n"+
 a.City+", "+a.State+" "+a.Zip+"n" } ! func (p *Person) String() string { return p.Name + "n" + p.Address.String() } Not Overloading
  • 32. func main() { p := Person{ Name: "Steve", Address: Address{ Number: "13", Street: "Main", City: "Gotham", State: "NY", Zip: "01313", }, } ! fmt.Println(p.String()) fmt.Println(p.Address.String()) } Both Methods Available http://play.golang.org/p/Aui0nGa5Xi
  • 33. func isValidAddress(a *Address) bool { return a.Street != "" } ! func main() { p := Person{ Name: "Steve", Address: Address{ Number: "13", Street: "Main", City: "Gotham", State: "NY", Zip: "01313"}} ! fmt.Println(isValidAddress(p)) 
 // cannot use p (type Person) as type Address 
 // in argument to isValidAddress fmt.Println(isValidAddress(p.Address)) } Types Remain Distinct http://play.golang.org/p/KYjXZxNBcQ
  • 35. Polymorphism • “The provision of a single interface to entities of different types” • Typically implmented via Generics, Overloading and/or Subtyping
  • 36. Go’s approach • Go explicitly avoided subtyping & overloading • Go does not provide Generics (yet) • Go’s interface provide polymorphic capabilities
  • 37. Interfaces • A list of required methods • Structural vs Nominal typing • ‘‘If something can do this, then it can be used here” • Convention is call it a Something-er
  • 38. type Shaper interface { Area() int } Interface Declaration
  • 39. func Describe(s Shaper) { fmt.Println("Area is:", s.Area()) } Using Interface as Param Type
  • 40. func main() { r := &Rect{width: 10, height: 5} x := &Rect{width: 7, height: 10} rs := &Rects{r, x} Describe(r) Describe(x) Describe(rs) } In Action http://play.golang.org/p/WL77LihUwi
  • 41. –James Gosling (creator of Java) “If you could do Java over again, what would you change?” “I’d leave out classes,” he replied. After the laughter died down, he explained that the real problem wasn’t classes per se, but rather implementation inheritance (the extends relationship). Interface inheritance (the implements relationship) is preferable. You should avoid implementation inheritance whenever possible.
  • 42. Go Interfaces are based on implementation, not declaration
  • 44. type Reader interface { Read(p []byte) (n int, err error) } io.Reader
  • 45. io.Reader • Interface • Read reads up to len(p) bytes into p • Returns the # of bytes read & any error • Does not dictate how Read() is implemented • Used by os.File, bytes.Buffer, net.Conn, http.Request.Body, loads more
  • 46. type Writer interface { Write(p []byte) (n int, err error) } io.Writer
  • 47. io.Writer • Interface • Write writes up to len(p) bytes into p • Returns the # of bytes written & any error • Does not dictate how Write() is implemented • Used by os.File, bytes.Buffer, net.Conn, http.Response.Body, loads more
  • 48. func MarshalGzippedJSON(r io.Reader, 
 v interface{}) error { raw, err := gzip.NewReader(r) if err != nil { return err } return json.NewDecoder(raw).Decode(&v) } io.Reader in Action
  • 49. f, err := os.Open("myfile.json.gz") if err != nil { log.Fatalln(err) } defer f.Close() m = make(map[string]interface{}) MarshalGzippedJSON(f, &m) Reading a json.gz file
  • 50. Practical Interoperability • Gzip.NewReader(io.Reader) • Works on files, http requests, byte buffers, network connections, …anything you create • Nothing special needed in gzip to be able to do this… Simply call Read(n) and leave the abstracting to the implementor
  • 51. func main() { resp, err := http.Get("...") if err != nil { log.Fatalln(err) } defer resp.Body.Close() out, err := os.Create("filename.ext") if err != nil { log.Fatalln(err) } defer out.Close() io.Copy(out, resp.Body) // out io.Writer, resp.Body io.Reader } Pipe http response to file
  • 52. Go
  • 53. — Steve Jobs Simple can be harder than complex: You have to work hard to get your thinking clean to make it simple. But it's worth it in the end because once you get there, you can move mountains.
  • 54. Go is simple, pratical & wonderful