SlideShare uma empresa Scribd logo
1 de 72
Baixar para ler offline
7 Common 
Mistakes 
In Go 
and when to avoid them
@Spf13 
Author of 
Hugo, Cobra, 
Afero, Viper & 
more
“As long as the 
world is turning 
and spinning, we're 
gonna be dizzy and 
we're gonna make 
mistakes.” 
–Mel Brooks
“Appreciate your 
mistakes for what 
they are: precious 
life lessons that 
can only be learned 
the hard way. “ 
–Al Franken
“If I had to live my 
life again, I'd make 
the same mistakes, 
only sooner.” 
– Tallulah Bankhead
7 Lessons 
I Wish I 
Learned 
Sooner
Mistake 1: 
Not 
Accepting 
Interfaces
State & Behavior 
•Types can express state & 
behavior 
•State = data structure 
•Behavior = methods
Interfaces 
•One of Go’s most powerful 
features 
•Permits extensibility 
•Defined by methods 
•Adherance is only satisfied by 
behavior
Example : []Byte 
type Source struct { 
Frontmatter []byte 
Content []byte 
}
Func Restricted To String 
func StripHTML(s string) string { 
output := "" 
// Shortcut strings with no tags in them 
if !strings.ContainsAny(s, "<>") { 
output = s 
} else { 
s = strings.Replace(s, "n", " ", -1) 
s = strings.Replace(s, "</p>", "n", -1) 
s = strings.Replace(s, "<br>", "n", -1) 
s = strings.Replace(s, "<br />", "n", -1) 
…
Passes Implementation 
Details Down The Stack 
func (p *Page) Plain() string { 
return helpers.StripHTML(string(p.Content)) 
}
Any Read() Works 
func StripHTML(r Reader) string { 
buf := new(bytes.Buffer) 
buf.ReadFrom(r) 
by := buf.Bytes() 
if bytes.ContainsAny(s, []byte("<>")) { 
by = bytes.Replace(by, []byte("n"), " ", -1) 
by = bytes.Replace(by, []byte("</p>"), "n", -1) 
by = bytes.Replace(by, []byte("<br>"), "n", -1) 
by = bytes.Replace(by, []byte("<br />"), "n", -1) 
…
type Source struct { 
Frontmatter []byte 
content []byte 
} 
type Reader interface { 
Read(p []byte) (n int, err error) 
} 
func (s *Source) Content() (Reader) { 
return bytes.NewReader(content) 
} 
Example : Read
type Source struct { 
Frontmatter []byte 
content []byte 
} 
type Reader interface { 
Read(p []byte) (n int, err error) 
} 
func (s *Source) Content() (Reader) { 
return bytes.NewReader(content) 
} 
Example : Read
type Source struct { 
Frontmatter []byte 
content []byte 
} 
type Reader interface { 
Read(p []byte) (n int, err error) 
} 
func (s *Source) Content() (Reader) { 
return bytes.NewReader(content) 
} 
Example : Read
func (p *Page) Plain() string { 
return helpers.StripHTML(p.Content()) 
} 
Implementation Details 
Abstracted With A Method
Mistake 2: 
Thinking Of 
Errors As 
Strings
Error Is An Interface 
type error interface { 
Error() string 
}
Standard Errors 
•errors.New(“error here”) is 
usually sufficient 
•Exported Error Variables 
can be easily checked
Custom Errors 
•Can provide context to 
guarantee consistent feedback 
•Provide a type which can be 
different from the error value 
•Can provide dynamic values 
(based on internal error state)
func NewPage(name string) (p *Page, 
err error) { 
if len(name) == 0 { 
return nil, 
errors.New("Zero length page name") 
} 
Standard Error
Exported Error Var 
var ErrNoName = errors.New("Zero length 
page name") 
func NewPage(name string) (*Page, error) 
{ 
if len(name) == 0 { 
return nil, ErrNoName 
}
Exported Error Var 
var ErrNoName = errors.New("Zero length page name") 
func Foo(name string) (error) { 
err := NewPage("bar") 
if err == ErrNoName { 
newPage("default") 
} else { 
log.FatalF(err) 
} 
}
Custom Errors : Os 
// Portable analogs of some common system call errors. 
var ErrInvalid = errors.New("invalid argument") 
var ErrPermission = errors.New("permission denied") 
// PathError records an error and 
// the operation and file path that caused it. 
type PathError struct { 
Op string 
Path string 
Err error 
} 
func (e *PathError) Error() string { 
return e.Op + " " + e.Path + ": " + e.Err.Error() 
}
Custom Errors : Os 
// Portable analogs of some common system call errors. 
var ErrInvalid = errors.New("invalid argument") 
var ErrPermission = errors.New("permission denied") 
// PathError records an error and 
// the operation and file path that caused it. 
type PathError struct { 
Op string 
Path string 
Err error 
} 
func (e *PathError) Error() string { 
return e.Op + " " + e.Path + ": " + e.Err.Error() 
}
Custom Errors : Os 
func (f *File) WriteAt(b []byte, off int64) (n int, err error) { 
if f == nil { 
return 0, ErrInvalid 
} 
for len(b) > 0 { 
m, e := f.pwrite(b, off) 
if e != nil { 
err = &PathError{"write", f.name, e} 
break 
} 
n += m 
b = b[m:] 
off += int64(m) 
} 
return 
}
Custom Errors : Os 
func (f *File) WriteAt(b []byte, off int64) (n int, err error) { 
if f == nil { 
return 0, ErrInvalid 
} 
for len(b) > 0 { 
m, e := f.pwrite(b, off) 
if e != nil { 
err = &PathError{"write", f.name, e} 
break 
} 
n += m 
b = b[m:] 
off += int64(m) 
} 
return 
}
Custom Errors : Os 
func (f *File) WriteAt(b []byte, off int64) (n int, err error) { 
if f == nil { 
return 0, ErrInvalid 
} 
for len(b) > 0 { 
m, e := f.pwrite(b, off) 
if e != nil { 
err = &PathError{"write", f.name, e} 
break 
} 
n += m 
b = b[m:] 
off += int64(m) 
} 
return 
}
Custom Errors : Os 
func baa(f *file) error { 
… 
n, err := f.WriteAt(x, 3) 
if _, ok := err.(*PathError) { 
… 
} else { 
log.Fatalf(err) 
} 
}
Custom Errors : Os 
… 
if serr != nil { 
if serr, ok := serr.(*PathError); ok && 
serr.Err == syscall.ENOTDIR { 
return nil 
} 
return serr 
…
Custom Errors : Os 
… 
if serr != nil { 
if serr, ok := serr.(*PathError); ok && 
serr.Err == syscall.ENOTDIR { 
return nil 
} 
return serr 
…
Mistake 3: 
Requring 
Broad 
Interfaces
Interfaces Are 
Composable 
•Functions should only accept interfaces 
that require the methods they need 
•Functions should not accept a broad 
interface when a narrow one would 
work 
•Compose broad interfaces made from 
narrower ones
Composing Interfaces 
type File interface { 
io.Closer 
io.Reader 
io.ReaderAt 
io.Seeker 
io.Writer 
io.WriterAt 
}
Requiring Broad Interfaces 
func ReadIn(f File) { 
b := []byte{} 
n, err := f.Read(b) 
... 
}
Composing Interfaces 
type File interface { 
io.Closer 
io.Reader 
io.ReaderAt 
io.Seeker 
io.Writer 
io.WriterAt 
}
Requiring Narrow Interfaces 
func ReadIn(r Reader) { 
b := []byte{} 
n, err := r.Read(b) 
... 
}
Mistake 4: 
Methods Vs 
Functions
Too Many Methods 
•A lot of people from OO 
backgrounds overuse 
methods 
•Natural draw to define 
everything via structs and 
methods
What Is A Function? 
•Operations performed on N1 
inputs that results in N2 outputs 
•The same inputs will always 
result in the same outputs 
•Functions should not depend on 
state
What Is A Method? 
•Defines the behavior of a type 
•A function that operates 
against a value 
•Should use state 
•Logically connected
Functions Can Be Used 
With Interfaces 
•Methods, by definition, are 
bound to a specific type 
•Functions can accept 
interfaces as input
Example From Hugo 
func extractShortcodes(s string, p *Page, t 
Template) (string, map[string]shortcode, error) { 
... 
for { 
switch currItem.typ { 
... 
case tError: 
err := fmt.Errorf("%s:%d: %s", 
p.BaseFileName(), 
(p.lineNumRawContentStart() 
+ pt.lexer.lineNum() - 1), currItem) 
} 
} 
... 
}
Example From Hugo 
func extractShortcodes(s string, p *Page, t 
Template) (string, map[string]shortcode, error) { 
... 
for { 
switch currItem.typ { 
... 
case tError: 
err := fmt.Errorf("%s:%d: %s", 
p.BaseFileName(), 
(p.lineNumRawContentStart() 
+ pt.lexer.lineNum() - 1), currItem) 
} 
} 
... 
}
Mistake 5: 
Pointers Vs 
Values
Pointers Vs Values 
•It’s not a question of performance 
(generally), but one of shared access 
•If you want to share the value with 
a function or method, then use a 
pointer 
•If you don’t want to share it, then 
use a value (copy)
Pointer Receivers 
•If you want to share a value with 
it’s method, use a pointer 
receiver 
•Since methods commonly manage 
state, this is the common usage 
•Not safe for concurrent access
Value Receivers 
•If you want the value copied 
(not shared), use values 
•If the type is an empty struct 
(stateless, just behavior)… 
then just use value 
•Safe for concurrent access
Afero File 
type InMemoryFile struct { 
at int64 
name string 
data []byte 
closed bool 
} 
func (f *InMemoryFile) Close() error { 
atomic.StoreInt64(&f.at, 0) 
f.closed = true 
return nil 
}
type Time struct { 
sec int64 
nsec uintptr 
loc *Location 
} 
func (t Time) IsZero() bool { 
return t.sec == 0 && t.nsec == 0 
} 
Time
Mistake 6: 
Not Using 
Io.Reader & 
Io.Writer
Io.Reader & Io.Writer 
•Simple & flexible interfaces 
for many operations around 
input and output 
•Provides access to a huge 
wealth of functionality 
•Keeps operations extensible
Io.Reader & Io.Writer 
type Reader interface { 
Read(p []byte) (n int, err error) 
} 
type Writer interface { 
Write(p []byte) (n int, err error) 
}
func (page *Page) saveSourceAs(path string) { 
b := new(bytes.Buffer) 
b.Write(page.Source.Content) 
page.saveSource(b.Bytes(), path) 
} 
func (page *Page) saveSource(by []byte, inpath 
string) { 
WriteToDisk(inpath, bytes.NewReader(by)) 
} 
Stop Doing This!!
func (page *Page) saveSourceAs(path string) { 
b := new(bytes.Buffer) 
b.Write(page.Source.Content) 
page.saveSource(b.Bytes(), path) 
} 
func (page *Page) saveSource(by []byte, inpath 
string) { 
WriteToDisk(inpath, bytes.NewReader(by)) 
} 
Stop Doing This!!
func (page *Page) saveSourceAs(path string) { 
b := new(bytes.Buffer) 
b.Write(page.Source.Content) 
page.saveSource(b.Bytes(), path) 
} 
func (page *Page) saveSource(by []byte, inpath 
string) { 
WriteToDisk(inpath, bytes.NewReader(by)) 
} 
Stop Doing This!! 
https://github.com/spf13/hugo/blob/master/hugolib/page.go#L582
func (page *Page) saveSourceAs(path string) { 
b := new(bytes.Buffer) 
b.Write(page.Source.Content) 
page.saveSource(b, path) 
} 
func (page *Page) saveSource(b io.Reader, inpath 
string) { 
WriteToDisk(inpath, b) 
} 
Instead
Mistake 7: 
Ignoring 
Concurrent 
Access
Consider Concurrency 
•If you provide a library someone 
will use it concurrently 
•Data structures are not safe for 
concurrent access 
•Values aren’t safe, you need to 
create safe behavior around them
Making It Safe 
•Sync package provides behavior 
to make a value safe (Atomic/ 
Mutex) 
•Channels cordinate values 
across go routines by permitting 
one go routine to access at a 
time
Maps Are Not Safe 
func (m *MMFs) Create(name string) (File, error) { 
m.getData()[name] = MemFileCreate(name) 
m.registerDirs(m.getData()[name]) 
return m.getData()[name], nil 
}
Maps Are Not Safe 
func (m *MMFS) Create(name string) (File, error) { 
m.getData()[name] = MemFileCreate(name) 
m.registerDirs(m.getData()[name]) 
return m.getData()[name], nil 
}
Maps Are Not Safe 
panic: runtime error: invalid memory address or nil 
pointer dereference 
[signal 0xb code=0x1 addr=0x28 pc=0x1691a7] 
goroutine 90 [running]: 
runtime.panic(0x501ea0, 0x86b104) 
/usr/local/Cellar/go/1.3.3/libexec/src/pkg/runtime/ 
panic.c:279 +0xf5 
github.com/spf13/afero. 
(*MemMapFs).registerDirs(0xc208000860, 0x0, 0x0) 
/Users/spf13/gopath/src/github.com/spf13/afero/ 
memmap.go:88 +0x27
Maps Can Be Used Safely 
func (m *MMFS) Create(name string) (File, error) { 
m.lock() 
m.getData()[name] = MemFileCreate(name) 
m.unlock() 
m.registerDirs(m.getData()[name]) 
return m.getData()[name], nil 
}
Biggsest 
Mistake: 
Not Makimg 
Mistakes
@Spf13 
Author of 
Hugo, Cobra, 
Afero, Viper & 
more

Mais conteúdo relacionado

Mais procurados

Vim Script Programming
Vim Script ProgrammingVim Script Programming
Vim Script ProgrammingLin Yo-An
 
Elegant concurrency
Elegant concurrencyElegant concurrency
Elegant concurrencyMosky Liu
 
Learning go for perl programmers
Learning go for perl programmersLearning go for perl programmers
Learning go for perl programmersFred Moyer
 
Learning Python from Data
Learning Python from DataLearning Python from Data
Learning Python from DataMosky Liu
 
Golang iran - tutorial go programming language - Preliminary
Golang iran - tutorial  go programming language - PreliminaryGolang iran - tutorial  go programming language - Preliminary
Golang iran - tutorial go programming language - Preliminarygo-lang
 
Go for Rubyists
Go for RubyistsGo for Rubyists
Go for Rubyiststchandy
 
PyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and MorePyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and MoreMatt Harrison
 
Beauty and Power of Go
Beauty and Power of GoBeauty and Power of Go
Beauty and Power of GoFrank Müller
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojureAbbas Raza
 
Why Python (for Statisticians)
Why Python (for Statisticians)Why Python (for Statisticians)
Why Python (for Statisticians)Matt Harrison
 
An Intro to Python in 30 minutes
An Intro to Python in 30 minutesAn Intro to Python in 30 minutes
An Intro to Python in 30 minutesSumit Raj
 
Python: an introduction for PHP webdevelopers
Python: an introduction for PHP webdevelopersPython: an introduction for PHP webdevelopers
Python: an introduction for PHP webdevelopersGlenn De Backer
 
Ruby for Java Developers
Ruby for Java DevelopersRuby for Java Developers
Ruby for Java DevelopersRobert Reiz
 

Mais procurados (20)

Vim Script Programming
Vim Script ProgrammingVim Script Programming
Vim Script Programming
 
Elegant concurrency
Elegant concurrencyElegant concurrency
Elegant concurrency
 
Learning go for perl programmers
Learning go for perl programmersLearning go for perl programmers
Learning go for perl programmers
 
IO Streams, Files and Directories
IO Streams, Files and DirectoriesIO Streams, Files and Directories
IO Streams, Files and Directories
 
Learning Python from Data
Learning Python from DataLearning Python from Data
Learning Python from Data
 
Golang iran - tutorial go programming language - Preliminary
Golang iran - tutorial  go programming language - PreliminaryGolang iran - tutorial  go programming language - Preliminary
Golang iran - tutorial go programming language - Preliminary
 
Go for Rubyists
Go for RubyistsGo for Rubyists
Go for Rubyists
 
Gcrc talk
Gcrc talkGcrc talk
Gcrc talk
 
Go Lang Tutorial
Go Lang TutorialGo Lang Tutorial
Go Lang Tutorial
 
PyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and MorePyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and More
 
Beauty and Power of Go
Beauty and Power of GoBeauty and Power of Go
Beauty and Power of Go
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojure
 
Why Python (for Statisticians)
Why Python (for Statisticians)Why Python (for Statisticians)
Why Python (for Statisticians)
 
iSoligorsk #3 2013
iSoligorsk #3 2013iSoligorsk #3 2013
iSoligorsk #3 2013
 
Advanced I/O in browser
Advanced I/O in browserAdvanced I/O in browser
Advanced I/O in browser
 
An Intro to Python in 30 minutes
An Intro to Python in 30 minutesAn Intro to Python in 30 minutes
An Intro to Python in 30 minutes
 
Python: an introduction for PHP webdevelopers
Python: an introduction for PHP webdevelopersPython: an introduction for PHP webdevelopers
Python: an introduction for PHP webdevelopers
 
IJTC%202009%20JRuby
IJTC%202009%20JRubyIJTC%202009%20JRuby
IJTC%202009%20JRuby
 
Ruby for Java Developers
Ruby for Java DevelopersRuby for Java Developers
Ruby for Java Developers
 
Golang
GolangGolang
Golang
 

Destaque

What every successful open source project needs
What every successful open source project needsWhat every successful open source project needs
What every successful open source project needsSteven Francia
 
The Future of the Operating System - Keynote LinuxCon 2015
The Future of the Operating System -  Keynote LinuxCon 2015The Future of the Operating System -  Keynote LinuxCon 2015
The Future of the Operating System - Keynote LinuxCon 2015Steven Francia
 
Build your first MongoDB App in Ruby @ StrangeLoop 2013
Build your first MongoDB App in Ruby @ StrangeLoop 2013Build your first MongoDB App in Ruby @ StrangeLoop 2013
Build your first MongoDB App in Ruby @ StrangeLoop 2013Steven Francia
 
Big data for the rest of us
Big data for the rest of usBig data for the rest of us
Big data for the rest of usSteven Francia
 
OSCON 2012 MongoDB Tutorial
OSCON 2012 MongoDB TutorialOSCON 2012 MongoDB Tutorial
OSCON 2012 MongoDB TutorialSteven Francia
 
MongoDB, Hadoop and humongous data - MongoSV 2012
MongoDB, Hadoop and humongous data - MongoSV 2012MongoDB, Hadoop and humongous data - MongoSV 2012
MongoDB, Hadoop and humongous data - MongoSV 2012Steven Francia
 
Distributed Programming and Data Consistency w/ Notes
Distributed Programming and Data Consistency w/ NotesDistributed Programming and Data Consistency w/ Notes
Distributed Programming and Data Consistency w/ NotesPaulo Gaspar
 
Audience for Career Counselling
Audience for Career CounsellingAudience for Career Counselling
Audience for Career CounsellingCareerGuide.com
 
So many different kinds of mistakes
So many different kinds of mistakesSo many different kinds of mistakes
So many different kinds of mistakesLiliana Davalos
 
Facts about Facebook
Facts about FacebookFacts about Facebook
Facts about Facebooksportela1
 
Large-scale Infrastructure Automation at Verizon
Large-scale Infrastructure Automation at VerizonLarge-scale Infrastructure Automation at Verizon
Large-scale Infrastructure Automation at VerizonTimothy Perrett
 
India Philippines, a relationship of opportunities
India Philippines, a relationship of opportunitiesIndia Philippines, a relationship of opportunities
India Philippines, a relationship of opportunitiesRaju Mandhyan
 
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 WorkshopSudhir Tonse
 
A World of Talent: What Perennial NBA Contenders Teach Us About Collaboration
A World of Talent: What Perennial NBA Contenders Teach Us About CollaborationA World of Talent: What Perennial NBA Contenders Teach Us About Collaboration
A World of Talent: What Perennial NBA Contenders Teach Us About CollaborationCureo
 

Destaque (19)

What every successful open source project needs
What every successful open source project needsWhat every successful open source project needs
What every successful open source project needs
 
The Future of the Operating System - Keynote LinuxCon 2015
The Future of the Operating System -  Keynote LinuxCon 2015The Future of the Operating System -  Keynote LinuxCon 2015
The Future of the Operating System - Keynote LinuxCon 2015
 
Build your first MongoDB App in Ruby @ StrangeLoop 2013
Build your first MongoDB App in Ruby @ StrangeLoop 2013Build your first MongoDB App in Ruby @ StrangeLoop 2013
Build your first MongoDB App in Ruby @ StrangeLoop 2013
 
Big data for the rest of us
Big data for the rest of usBig data for the rest of us
Big data for the rest of us
 
OSCON 2012 MongoDB Tutorial
OSCON 2012 MongoDB TutorialOSCON 2012 MongoDB Tutorial
OSCON 2012 MongoDB Tutorial
 
MongoDB, Hadoop and humongous data - MongoSV 2012
MongoDB, Hadoop and humongous data - MongoSV 2012MongoDB, Hadoop and humongous data - MongoSV 2012
MongoDB, Hadoop and humongous data - MongoSV 2012
 
Gophercon 2016 recap
Gophercon 2016 recapGophercon 2016 recap
Gophercon 2016 recap
 
Distributed Programming and Data Consistency w/ Notes
Distributed Programming and Data Consistency w/ NotesDistributed Programming and Data Consistency w/ Notes
Distributed Programming and Data Consistency w/ Notes
 
Serialization in Go
Serialization in GoSerialization in Go
Serialization in Go
 
Audience for Career Counselling
Audience for Career CounsellingAudience for Career Counselling
Audience for Career Counselling
 
So many different kinds of mistakes
So many different kinds of mistakesSo many different kinds of mistakes
So many different kinds of mistakes
 
Facts about Facebook
Facts about FacebookFacts about Facebook
Facts about Facebook
 
Large-scale Infrastructure Automation at Verizon
Large-scale Infrastructure Automation at VerizonLarge-scale Infrastructure Automation at Verizon
Large-scale Infrastructure Automation at Verizon
 
India Philippines, a relationship of opportunities
India Philippines, a relationship of opportunitiesIndia Philippines, a relationship of opportunities
India Philippines, a relationship of opportunities
 
10 Tips to Improve Your Proofreading
10 Tips to Improve Your Proofreading10 Tips to Improve Your Proofreading
10 Tips to Improve Your Proofreading
 
6 Security Tips for Using Public WiFi
6 Security Tips for Using Public WiFi6 Security Tips for Using Public WiFi
6 Security Tips for Using Public WiFi
 
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
 
A World of Talent: What Perennial NBA Contenders Teach Us About Collaboration
A World of Talent: What Perennial NBA Contenders Teach Us About CollaborationA World of Talent: What Perennial NBA Contenders Teach Us About Collaboration
A World of Talent: What Perennial NBA Contenders Teach Us About Collaboration
 
Thanks for Making That Mistake! Using Errors as an Interpreter Teaching Tool
Thanks for Making That Mistake! Using Errors as an Interpreter Teaching ToolThanks for Making That Mistake! Using Errors as an Interpreter Teaching Tool
Thanks for Making That Mistake! Using Errors as an Interpreter Teaching Tool
 

Semelhante a 7 Common mistakes in Go and when to avoid them

Fantom - Programming Language for JVM, CLR, and Javascript
Fantom - Programming Language for JVM, CLR, and JavascriptFantom - Programming Language for JVM, CLR, and Javascript
Fantom - Programming Language for JVM, CLR, and JavascriptKamil Toman
 
Fantom on the JVM Devoxx09 BOF
Fantom on the JVM Devoxx09 BOFFantom on the JVM Devoxx09 BOF
Fantom on the JVM Devoxx09 BOFDror Bereznitsky
 
How to avoid Go gotchas - Ivan Daniluk - Codemotion Milan 2016
How to avoid Go gotchas - Ivan Daniluk - Codemotion Milan 2016How to avoid Go gotchas - Ivan Daniluk - Codemotion Milan 2016
How to avoid Go gotchas - Ivan Daniluk - Codemotion Milan 2016Codemotion
 
Jedi Slides Intro2 Chapter12 Advanced Io Streams
Jedi Slides Intro2 Chapter12 Advanced Io StreamsJedi Slides Intro2 Chapter12 Advanced Io Streams
Jedi Slides Intro2 Chapter12 Advanced Io StreamsDon Bosco BSIT
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard LibrarySantosh Rajan
 
Input/Output Exploring java.io
Input/Output Exploring java.ioInput/Output Exploring java.io
Input/Output Exploring java.ioNilaNila16
 
CodeFest 2010. Иноземцев И. — Fantom. Cross-VM Language
CodeFest 2010. Иноземцев И. — Fantom. Cross-VM LanguageCodeFest 2010. Иноземцев И. — Fantom. Cross-VM Language
CodeFest 2010. Иноземцев И. — Fantom. Cross-VM LanguageCodeFest
 
Geeks Anonymes - Le langage Go
Geeks Anonymes - Le langage GoGeeks Anonymes - Le langage Go
Geeks Anonymes - Le langage GoGeeks Anonymes
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayUtkarsh Sengar
 
golang_refcard.pdf
golang_refcard.pdfgolang_refcard.pdf
golang_refcard.pdfSpam92
 
Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, SwiftYandex
 
Os Vanrossum
Os VanrossumOs Vanrossum
Os Vanrossumoscon2007
 
Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017
Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017
Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017Codemotion
 

Semelhante a 7 Common mistakes in Go and when to avoid them (20)

Quick swift tour
Quick swift tourQuick swift tour
Quick swift tour
 
Gunosy.go #4 go
Gunosy.go #4 goGunosy.go #4 go
Gunosy.go #4 go
 
Fantom - Programming Language for JVM, CLR, and Javascript
Fantom - Programming Language for JVM, CLR, and JavascriptFantom - Programming Language for JVM, CLR, and Javascript
Fantom - Programming Language for JVM, CLR, and Javascript
 
Fantom on the JVM Devoxx09 BOF
Fantom on the JVM Devoxx09 BOFFantom on the JVM Devoxx09 BOF
Fantom on the JVM Devoxx09 BOF
 
Fun with functions
Fun with functionsFun with functions
Fun with functions
 
How to avoid Go gotchas - Ivan Daniluk - Codemotion Milan 2016
How to avoid Go gotchas - Ivan Daniluk - Codemotion Milan 2016How to avoid Go gotchas - Ivan Daniluk - Codemotion Milan 2016
How to avoid Go gotchas - Ivan Daniluk - Codemotion Milan 2016
 
Java 8 new features
Java 8 new featuresJava 8 new features
Java 8 new features
 
Jedi Slides Intro2 Chapter12 Advanced Io Streams
Jedi Slides Intro2 Chapter12 Advanced Io StreamsJedi Slides Intro2 Chapter12 Advanced Io Streams
Jedi Slides Intro2 Chapter12 Advanced Io Streams
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard Library
 
Input/Output Exploring java.io
Input/Output Exploring java.ioInput/Output Exploring java.io
Input/Output Exploring java.io
 
CodeFest 2010. Иноземцев И. — Fantom. Cross-VM Language
CodeFest 2010. Иноземцев И. — Fantom. Cross-VM LanguageCodeFest 2010. Иноземцев И. — Fantom. Cross-VM Language
CodeFest 2010. Иноземцев И. — Fantom. Cross-VM Language
 
Geeks Anonymes - Le langage Go
Geeks Anonymes - Le langage GoGeeks Anonymes - Le langage Go
Geeks Anonymes - Le langage Go
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
 
golang_refcard.pdf
golang_refcard.pdfgolang_refcard.pdf
golang_refcard.pdf
 
Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, Swift
 
Os Vanrossum
Os VanrossumOs Vanrossum
Os Vanrossum
 
Dynamic Python
Dynamic PythonDynamic Python
Dynamic Python
 
Java I/O
Java I/OJava I/O
Java I/O
 
Introduction to Go
Introduction to GoIntroduction to Go
Introduction to Go
 
Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017
Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017
Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017
 

Mais de Steven Francia

State of the Gopher Nation - Golang - August 2017
State of the Gopher Nation - Golang - August 2017State of the Gopher Nation - Golang - August 2017
State of the Gopher Nation - Golang - August 2017Steven Francia
 
Modern Database Systems (for Genealogy)
Modern Database Systems (for Genealogy)Modern Database Systems (for Genealogy)
Modern Database Systems (for Genealogy)Steven Francia
 
Introduction to MongoDB and Hadoop
Introduction to MongoDB and HadoopIntroduction to MongoDB and Hadoop
Introduction to MongoDB and HadoopSteven Francia
 
Replication, Durability, and Disaster Recovery
Replication, Durability, and Disaster RecoveryReplication, Durability, and Disaster Recovery
Replication, Durability, and Disaster RecoverySteven Francia
 
Multi Data Center Strategies
Multi Data Center StrategiesMulti Data Center Strategies
Multi Data Center StrategiesSteven Francia
 
NoSQL databases and managing big data
NoSQL databases and managing big dataNoSQL databases and managing big data
NoSQL databases and managing big dataSteven Francia
 
MongoDB, Hadoop and Humongous Data
MongoDB, Hadoop and Humongous DataMongoDB, Hadoop and Humongous Data
MongoDB, Hadoop and Humongous DataSteven Francia
 
Hybrid MongoDB and RDBMS Applications
Hybrid MongoDB and RDBMS ApplicationsHybrid MongoDB and RDBMS Applications
Hybrid MongoDB and RDBMS ApplicationsSteven Francia
 
Building your first application w/mongoDB MongoSV2011
Building your first application w/mongoDB MongoSV2011Building your first application w/mongoDB MongoSV2011
Building your first application w/mongoDB MongoSV2011Steven Francia
 
MongoDB, E-commerce and Transactions
MongoDB, E-commerce and TransactionsMongoDB, E-commerce and Transactions
MongoDB, E-commerce and TransactionsSteven Francia
 
MongoDB, PHP and the cloud - php cloud summit 2011
MongoDB, PHP and the cloud - php cloud summit 2011MongoDB, PHP and the cloud - php cloud summit 2011
MongoDB, PHP and the cloud - php cloud summit 2011Steven Francia
 
MongoDB and PHP ZendCon 2011
MongoDB and PHP ZendCon 2011MongoDB and PHP ZendCon 2011
MongoDB and PHP ZendCon 2011Steven Francia
 
Blending MongoDB and RDBMS for ecommerce
Blending MongoDB and RDBMS for ecommerceBlending MongoDB and RDBMS for ecommerce
Blending MongoDB and RDBMS for ecommerceSteven Francia
 
Augmenting RDBMS with MongoDB for ecommerce
Augmenting RDBMS with MongoDB for ecommerceAugmenting RDBMS with MongoDB for ecommerce
Augmenting RDBMS with MongoDB for ecommerceSteven Francia
 
MongoDB and Ecommerce : A perfect combination
MongoDB and Ecommerce : A perfect combinationMongoDB and Ecommerce : A perfect combination
MongoDB and Ecommerce : A perfect combinationSteven Francia
 

Mais de Steven Francia (19)

State of the Gopher Nation - Golang - August 2017
State of the Gopher Nation - Golang - August 2017State of the Gopher Nation - Golang - August 2017
State of the Gopher Nation - Golang - August 2017
 
Modern Database Systems (for Genealogy)
Modern Database Systems (for Genealogy)Modern Database Systems (for Genealogy)
Modern Database Systems (for Genealogy)
 
Introduction to MongoDB and Hadoop
Introduction to MongoDB and HadoopIntroduction to MongoDB and Hadoop
Introduction to MongoDB and Hadoop
 
Future of data
Future of dataFuture of data
Future of data
 
Replication, Durability, and Disaster Recovery
Replication, Durability, and Disaster RecoveryReplication, Durability, and Disaster Recovery
Replication, Durability, and Disaster Recovery
 
Multi Data Center Strategies
Multi Data Center StrategiesMulti Data Center Strategies
Multi Data Center Strategies
 
NoSQL databases and managing big data
NoSQL databases and managing big dataNoSQL databases and managing big data
NoSQL databases and managing big data
 
MongoDB, Hadoop and Humongous Data
MongoDB, Hadoop and Humongous DataMongoDB, Hadoop and Humongous Data
MongoDB, Hadoop and Humongous Data
 
MongoDB and hadoop
MongoDB and hadoopMongoDB and hadoop
MongoDB and hadoop
 
MongoDB for Genealogy
MongoDB for GenealogyMongoDB for Genealogy
MongoDB for Genealogy
 
Hybrid MongoDB and RDBMS Applications
Hybrid MongoDB and RDBMS ApplicationsHybrid MongoDB and RDBMS Applications
Hybrid MongoDB and RDBMS Applications
 
Building your first application w/mongoDB MongoSV2011
Building your first application w/mongoDB MongoSV2011Building your first application w/mongoDB MongoSV2011
Building your first application w/mongoDB MongoSV2011
 
MongoDB, E-commerce and Transactions
MongoDB, E-commerce and TransactionsMongoDB, E-commerce and Transactions
MongoDB, E-commerce and Transactions
 
MongoDB, PHP and the cloud - php cloud summit 2011
MongoDB, PHP and the cloud - php cloud summit 2011MongoDB, PHP and the cloud - php cloud summit 2011
MongoDB, PHP and the cloud - php cloud summit 2011
 
MongoDB and PHP ZendCon 2011
MongoDB and PHP ZendCon 2011MongoDB and PHP ZendCon 2011
MongoDB and PHP ZendCon 2011
 
MongoDB
MongoDBMongoDB
MongoDB
 
Blending MongoDB and RDBMS for ecommerce
Blending MongoDB and RDBMS for ecommerceBlending MongoDB and RDBMS for ecommerce
Blending MongoDB and RDBMS for ecommerce
 
Augmenting RDBMS with MongoDB for ecommerce
Augmenting RDBMS with MongoDB for ecommerceAugmenting RDBMS with MongoDB for ecommerce
Augmenting RDBMS with MongoDB for ecommerce
 
MongoDB and Ecommerce : A perfect combination
MongoDB and Ecommerce : A perfect combinationMongoDB and Ecommerce : A perfect combination
MongoDB and Ecommerce : A perfect combination
 

Último

SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...Akihiro Suda
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 

Último (20)

SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 

7 Common mistakes in Go and when to avoid them

  • 1. 7 Common Mistakes In Go and when to avoid them
  • 2. @Spf13 Author of Hugo, Cobra, Afero, Viper & more
  • 3. “As long as the world is turning and spinning, we're gonna be dizzy and we're gonna make mistakes.” –Mel Brooks
  • 4. “Appreciate your mistakes for what they are: precious life lessons that can only be learned the hard way. “ –Al Franken
  • 5. “If I had to live my life again, I'd make the same mistakes, only sooner.” – Tallulah Bankhead
  • 6. 7 Lessons I Wish I Learned Sooner
  • 7. Mistake 1: Not Accepting Interfaces
  • 8. State & Behavior •Types can express state & behavior •State = data structure •Behavior = methods
  • 9. Interfaces •One of Go’s most powerful features •Permits extensibility •Defined by methods •Adherance is only satisfied by behavior
  • 10.
  • 11. Example : []Byte type Source struct { Frontmatter []byte Content []byte }
  • 12. Func Restricted To String func StripHTML(s string) string { output := "" // Shortcut strings with no tags in them if !strings.ContainsAny(s, "<>") { output = s } else { s = strings.Replace(s, "n", " ", -1) s = strings.Replace(s, "</p>", "n", -1) s = strings.Replace(s, "<br>", "n", -1) s = strings.Replace(s, "<br />", "n", -1) …
  • 13. Passes Implementation Details Down The Stack func (p *Page) Plain() string { return helpers.StripHTML(string(p.Content)) }
  • 14. Any Read() Works func StripHTML(r Reader) string { buf := new(bytes.Buffer) buf.ReadFrom(r) by := buf.Bytes() if bytes.ContainsAny(s, []byte("<>")) { by = bytes.Replace(by, []byte("n"), " ", -1) by = bytes.Replace(by, []byte("</p>"), "n", -1) by = bytes.Replace(by, []byte("<br>"), "n", -1) by = bytes.Replace(by, []byte("<br />"), "n", -1) …
  • 15. type Source struct { Frontmatter []byte content []byte } type Reader interface { Read(p []byte) (n int, err error) } func (s *Source) Content() (Reader) { return bytes.NewReader(content) } Example : Read
  • 16. type Source struct { Frontmatter []byte content []byte } type Reader interface { Read(p []byte) (n int, err error) } func (s *Source) Content() (Reader) { return bytes.NewReader(content) } Example : Read
  • 17. type Source struct { Frontmatter []byte content []byte } type Reader interface { Read(p []byte) (n int, err error) } func (s *Source) Content() (Reader) { return bytes.NewReader(content) } Example : Read
  • 18. func (p *Page) Plain() string { return helpers.StripHTML(p.Content()) } Implementation Details Abstracted With A Method
  • 19. Mistake 2: Thinking Of Errors As Strings
  • 20. Error Is An Interface type error interface { Error() string }
  • 21. Standard Errors •errors.New(“error here”) is usually sufficient •Exported Error Variables can be easily checked
  • 22. Custom Errors •Can provide context to guarantee consistent feedback •Provide a type which can be different from the error value •Can provide dynamic values (based on internal error state)
  • 23. func NewPage(name string) (p *Page, err error) { if len(name) == 0 { return nil, errors.New("Zero length page name") } Standard Error
  • 24. Exported Error Var var ErrNoName = errors.New("Zero length page name") func NewPage(name string) (*Page, error) { if len(name) == 0 { return nil, ErrNoName }
  • 25. Exported Error Var var ErrNoName = errors.New("Zero length page name") func Foo(name string) (error) { err := NewPage("bar") if err == ErrNoName { newPage("default") } else { log.FatalF(err) } }
  • 26. Custom Errors : Os // Portable analogs of some common system call errors. var ErrInvalid = errors.New("invalid argument") var ErrPermission = errors.New("permission denied") // PathError records an error and // the operation and file path that caused it. type PathError struct { Op string Path string Err error } func (e *PathError) Error() string { return e.Op + " " + e.Path + ": " + e.Err.Error() }
  • 27. Custom Errors : Os // Portable analogs of some common system call errors. var ErrInvalid = errors.New("invalid argument") var ErrPermission = errors.New("permission denied") // PathError records an error and // the operation and file path that caused it. type PathError struct { Op string Path string Err error } func (e *PathError) Error() string { return e.Op + " " + e.Path + ": " + e.Err.Error() }
  • 28. Custom Errors : Os func (f *File) WriteAt(b []byte, off int64) (n int, err error) { if f == nil { return 0, ErrInvalid } for len(b) > 0 { m, e := f.pwrite(b, off) if e != nil { err = &PathError{"write", f.name, e} break } n += m b = b[m:] off += int64(m) } return }
  • 29. Custom Errors : Os func (f *File) WriteAt(b []byte, off int64) (n int, err error) { if f == nil { return 0, ErrInvalid } for len(b) > 0 { m, e := f.pwrite(b, off) if e != nil { err = &PathError{"write", f.name, e} break } n += m b = b[m:] off += int64(m) } return }
  • 30. Custom Errors : Os func (f *File) WriteAt(b []byte, off int64) (n int, err error) { if f == nil { return 0, ErrInvalid } for len(b) > 0 { m, e := f.pwrite(b, off) if e != nil { err = &PathError{"write", f.name, e} break } n += m b = b[m:] off += int64(m) } return }
  • 31. Custom Errors : Os func baa(f *file) error { … n, err := f.WriteAt(x, 3) if _, ok := err.(*PathError) { … } else { log.Fatalf(err) } }
  • 32. Custom Errors : Os … if serr != nil { if serr, ok := serr.(*PathError); ok && serr.Err == syscall.ENOTDIR { return nil } return serr …
  • 33. Custom Errors : Os … if serr != nil { if serr, ok := serr.(*PathError); ok && serr.Err == syscall.ENOTDIR { return nil } return serr …
  • 34. Mistake 3: Requring Broad Interfaces
  • 35. Interfaces Are Composable •Functions should only accept interfaces that require the methods they need •Functions should not accept a broad interface when a narrow one would work •Compose broad interfaces made from narrower ones
  • 36.
  • 37. Composing Interfaces type File interface { io.Closer io.Reader io.ReaderAt io.Seeker io.Writer io.WriterAt }
  • 38. Requiring Broad Interfaces func ReadIn(f File) { b := []byte{} n, err := f.Read(b) ... }
  • 39. Composing Interfaces type File interface { io.Closer io.Reader io.ReaderAt io.Seeker io.Writer io.WriterAt }
  • 40. Requiring Narrow Interfaces func ReadIn(r Reader) { b := []byte{} n, err := r.Read(b) ... }
  • 41. Mistake 4: Methods Vs Functions
  • 42. Too Many Methods •A lot of people from OO backgrounds overuse methods •Natural draw to define everything via structs and methods
  • 43. What Is A Function? •Operations performed on N1 inputs that results in N2 outputs •The same inputs will always result in the same outputs •Functions should not depend on state
  • 44. What Is A Method? •Defines the behavior of a type •A function that operates against a value •Should use state •Logically connected
  • 45. Functions Can Be Used With Interfaces •Methods, by definition, are bound to a specific type •Functions can accept interfaces as input
  • 46.
  • 47. Example From Hugo func extractShortcodes(s string, p *Page, t Template) (string, map[string]shortcode, error) { ... for { switch currItem.typ { ... case tError: err := fmt.Errorf("%s:%d: %s", p.BaseFileName(), (p.lineNumRawContentStart() + pt.lexer.lineNum() - 1), currItem) } } ... }
  • 48. Example From Hugo func extractShortcodes(s string, p *Page, t Template) (string, map[string]shortcode, error) { ... for { switch currItem.typ { ... case tError: err := fmt.Errorf("%s:%d: %s", p.BaseFileName(), (p.lineNumRawContentStart() + pt.lexer.lineNum() - 1), currItem) } } ... }
  • 49. Mistake 5: Pointers Vs Values
  • 50. Pointers Vs Values •It’s not a question of performance (generally), but one of shared access •If you want to share the value with a function or method, then use a pointer •If you don’t want to share it, then use a value (copy)
  • 51. Pointer Receivers •If you want to share a value with it’s method, use a pointer receiver •Since methods commonly manage state, this is the common usage •Not safe for concurrent access
  • 52. Value Receivers •If you want the value copied (not shared), use values •If the type is an empty struct (stateless, just behavior)… then just use value •Safe for concurrent access
  • 53. Afero File type InMemoryFile struct { at int64 name string data []byte closed bool } func (f *InMemoryFile) Close() error { atomic.StoreInt64(&f.at, 0) f.closed = true return nil }
  • 54. type Time struct { sec int64 nsec uintptr loc *Location } func (t Time) IsZero() bool { return t.sec == 0 && t.nsec == 0 } Time
  • 55. Mistake 6: Not Using Io.Reader & Io.Writer
  • 56. Io.Reader & Io.Writer •Simple & flexible interfaces for many operations around input and output •Provides access to a huge wealth of functionality •Keeps operations extensible
  • 57. Io.Reader & Io.Writer type Reader interface { Read(p []byte) (n int, err error) } type Writer interface { Write(p []byte) (n int, err error) }
  • 58.
  • 59. func (page *Page) saveSourceAs(path string) { b := new(bytes.Buffer) b.Write(page.Source.Content) page.saveSource(b.Bytes(), path) } func (page *Page) saveSource(by []byte, inpath string) { WriteToDisk(inpath, bytes.NewReader(by)) } Stop Doing This!!
  • 60. func (page *Page) saveSourceAs(path string) { b := new(bytes.Buffer) b.Write(page.Source.Content) page.saveSource(b.Bytes(), path) } func (page *Page) saveSource(by []byte, inpath string) { WriteToDisk(inpath, bytes.NewReader(by)) } Stop Doing This!!
  • 61. func (page *Page) saveSourceAs(path string) { b := new(bytes.Buffer) b.Write(page.Source.Content) page.saveSource(b.Bytes(), path) } func (page *Page) saveSource(by []byte, inpath string) { WriteToDisk(inpath, bytes.NewReader(by)) } Stop Doing This!! https://github.com/spf13/hugo/blob/master/hugolib/page.go#L582
  • 62. func (page *Page) saveSourceAs(path string) { b := new(bytes.Buffer) b.Write(page.Source.Content) page.saveSource(b, path) } func (page *Page) saveSource(b io.Reader, inpath string) { WriteToDisk(inpath, b) } Instead
  • 63. Mistake 7: Ignoring Concurrent Access
  • 64. Consider Concurrency •If you provide a library someone will use it concurrently •Data structures are not safe for concurrent access •Values aren’t safe, you need to create safe behavior around them
  • 65. Making It Safe •Sync package provides behavior to make a value safe (Atomic/ Mutex) •Channels cordinate values across go routines by permitting one go routine to access at a time
  • 66.
  • 67. Maps Are Not Safe func (m *MMFs) Create(name string) (File, error) { m.getData()[name] = MemFileCreate(name) m.registerDirs(m.getData()[name]) return m.getData()[name], nil }
  • 68. Maps Are Not Safe func (m *MMFS) Create(name string) (File, error) { m.getData()[name] = MemFileCreate(name) m.registerDirs(m.getData()[name]) return m.getData()[name], nil }
  • 69. Maps Are Not Safe panic: runtime error: invalid memory address or nil pointer dereference [signal 0xb code=0x1 addr=0x28 pc=0x1691a7] goroutine 90 [running]: runtime.panic(0x501ea0, 0x86b104) /usr/local/Cellar/go/1.3.3/libexec/src/pkg/runtime/ panic.c:279 +0xf5 github.com/spf13/afero. (*MemMapFs).registerDirs(0xc208000860, 0x0, 0x0) /Users/spf13/gopath/src/github.com/spf13/afero/ memmap.go:88 +0x27
  • 70. Maps Can Be Used Safely func (m *MMFS) Create(name string) (File, error) { m.lock() m.getData()[name] = MemFileCreate(name) m.unlock() m.registerDirs(m.getData()[name]) return m.getData()[name], nil }
  • 71. Biggsest Mistake: Not Makimg Mistakes
  • 72. @Spf13 Author of Hugo, Cobra, Afero, Viper & more