8. Go.2 - Un po’ di storia
Meetup Golang Milano - 27 Settembre 2018
September 25
Pike, Griesemer,
Thompson,
scelgono il nome "Go"
November 10
Prima release open
source del compilatore
Golang
October 5
Prime proposte
per la prima release
March 28
Release Go 1!
go1.1
go1.2
go1.3
go1.4
go1.5
go1.6
go1.7
go1.8
go1.9
go1.10
go1.11
2007
2018
2011
2009
2013
2014
2015
2016
2017
2012
Source: https://golang.org/doc/devel/release.html
9. Go.2 - Release Cycle in Go
Meetup Golang Milano - 27 Settembre 2018
! major release every six
months
! three months of general
development followed
by three months of
testing and polishing
known as the release
freeze
Source: Go release cycle
https://github.com/golang/go/wiki/Go-Release-Cycle
10. Go.2 - Processo di evoluzione
Meetup Golang Milano - 27 Settembre 2018
Source: The future of go - Russ Cox - 2017
11. Go.2 - Processo di evoluzione
Meetup Golang Milano - 27 Settembre 2018
Source: The future of go - Russ Cox - 2017
12. {
Go.2 - Vincoli di evoluzione
Vincoli
keywords
+
compatibility
Meetup Golang Milano - 27 Settembre 2018
13. Go.2 - Ma a noi…
Meetup Golang Milano - 27 Settembre 2018
E a noi cosa interessa tutto questo?
14. Go.2 - Ma a noi… interessa in prima persona!
Meetup Golang Milano - 27 Settembre 2018
Tutte le nuove feature
seguono questo
processo, ma nascono
dalla community.
15. Go.2 - Community - Come decidere cosa è importante
Meetup Golang Milano - 27 Settembre 2018
Experience Reports
App and Game Development
Concurrency
Casting
Context Declarations
Dependencies
Documentation
Diagnostics and Debugging
Education and Teaching
Error Handling
File System
Generics
Immutability
Inter Process Communication
Large-Scale Software Development
Logging
Modules
Performance
Porting
Slices
Syntax
Time
Tooling
Type System
Typed nils
Vendoring
Source: https://github.com/golang/go/wiki/ExperienceReports
16. Go.2 - Community - Come decidere cosa è importante
Meetup Golang Milano - 27 Settembre 2018
Experience Reports
App and Game Development
Concurrency
Casting
Context Declarations
Dependencies
Documentation
Diagnostics and Debugging
Education and Teaching
Error Handling
File System
Generics
Immutability
Inter Process Communication
Large-Scale Software Development
Logging
Modules
Performance
Porting
Slices
Syntax
Time
Tooling
Type System
Typed nils
Vendoring
Go 1.9
Go 1.11
Go 1.11
Go 1.9
Source: https://github.com/golang/go/wiki/ExperienceReports
17. Go - Survey 2016
Meetup Golang Milano - 27 Settembre 2018
Source: https://blog.golang.org/survey2016-results
18. Go Survey 2017
Meetup Golang Milano - 27 Settembre 2018
Source: https://blog.golang.org/survey2017-results
19. Go Survey 2017 - Contributo
Meetup Golang Milano - 27 Settembre 2018
Recap prima delle proposte per Go 2:
- Go evolve rapidamente (~2 release all’anno)
- Ci sono dei vincoli precisi: keywords e compatibilità
- Il processo è chiaro e preciso.
- L’esperienza della community è importante!
(expeience reports)
(leap second di Cloudflare)
- La community è ascoltata!
(survey 2016: package & version management -> vgo e moduli)
(survey 2017: generics, errors and error handling)
- Che comunque non è solo community driven ma le decisioni
importanti non vengono prese alla leggera
( Pike, Griesemer, Thompson, Cox… & Google)
Possiamo contribuire anche noi! Sia con experience reports,
sia partecipando alla survey di dicembre!
23. Experience reports on Error Handling
Error Handling - Experience Reports
Meetup Golang Milano - 27 Settembre 2018
8
24. Experience reports on Error Handling
Error Handling - Experience Reports
Meetup Golang Milano - 27 Settembre 2018
Andrew Morgan - January 2017
“ About it being difficult to force good
error handling, errors not having stack
traces and error handling being too
verbose. ”
Peter Goetz - 2017
“ The error handling mechanism should:
- Force the developer to handle errors
- Have local scopes for errors to avoid
handling mistakes
- Have an expressive syntax
- Have a simple syntax to “fail fast” ”
25. Error Handling - Nice, clean, elegant code
func CopyFile(src, dst string) throws error {
r := os.Open(src)
defer r.Close()
w := os.Create(dst)
io.Copy(w, r)
w.Close()
}
Ipotetico dialetto Go con eccezioni:
Nice, clean
and elegant.
(and wrong)
Meetup Golang Milano - 27 Settembre 2018
26. Error Handling - Nice, clean, elegant code
func CopyFile(src, dst string) error {
r, err := os.Open(src)
if err != nil {
return err
}
defer r.Close()
w, err := os.Create(dst)
if err != nil {
return err
}
defer w.Close()
if _, err := io.Copy(w, r); err != nil {
return err
}
if err := w.Close(); err != nil {
return err
}
}
Equivalente in Go:
Not nice,
Not clean and
Not elegant.
(and wrong)
Meetup Golang Milano - 27 Settembre 2018
27. Error Handling - Nice, clean, elegant code
func CopyFile(src, dst string) error {
r, err := os.Open(src)
if err != nil {
return fmt.Errorf("copy %s %s: %v", src, dst, err)
}
defer r.Close()
w, err := os.Create(dst)
if err != nil {
return fmt.Errorf("copy %s %s: %v", src, dst, err)
}
if _, err := io.Copy(w, r); err != nil {
w.Close()
os.Remove(dst)
return fmt.Errorf("copy %s %s: %v", src, dst, err)
}
if err := w.Close(); err != nil {
os.Remove(dst)
return fmt.Errorf("copy %s %s: %v", src, dst, err)
}
}
Equivalente in Go (corretto):
Not nice,
Not clean and
Not elegant.
(and correct!)
Meetup Golang Milano - 27 Settembre 2018
28. Obiettivi per Go 2
Error Handling - Obiettivi
Meetup Golang Milano - 27 Settembre 2018
- Error check più leggero
- Gestione più agile
Ricordandosi i vincoli!
il codice attuale deve rimanere valido.
29. Proposta
Error Handling - Proposta
Meetup Golang Milano - 27 Settembre 2018
2 nuove keywords: check e handle
30. Error Handling - Nice, clean, elegant code
func CopyFile(src, dst string) error {
handle err {
return fmt.Errorf("copy %s %s: %v", src, dst,
err)
}
r := check os.Open(src)
defer r.Close()
w := check os.Create(dst)
handle err {
w.Close()
os.Remove(dst) // (only if a check fails)
}
check io.Copy(w, r)
check w.Close()
return nil
}
Esempio check/handle:
Nice?
Clean?
Elegant?
(but correct!)
Meetup Golang Milano - 27 Settembre 2018
31. Meetup Golang Milano - 27 Settembre 2018
Error Handling - Confronto
func main() {
hex, err := ioutil.ReadAll(os.Stdin)
if err != nil {
log.Fatal(err)
}
data, err := parseHexdump(string(hex))
if err != nil {
log.Fatal(err)
}
os.Stdout.Write(data)
}
func main() {
handle err {
log.Fatal(err)
}
hex := check ioutil.ReadAll(os.Stdin)
data := check parseHexdump(string(hex))
os.Stdout.Write(data)
}
Go 1.11 Go 2
32. Error Handling - Critiche e domande
Meetup Golang Milano - 27 Settembre 2018
! A questo punto usiamo try/catch
! L’error handling gestito così è simile ad averlo
in un defer-recover
! E i panics?
Fonti: https://github.com/golang/go/wiki/
Go2ErrorHandlingFeedback (44 contributi)
35. Experience reports on Errors + Handling
Errors - Experience Reports
Meetup Golang Milano - 27 Settembre 2018
2+8 = 10
36. Experience reports on Errors
Errors - Experience Reports
Meetup Golang Milano - 27 Settembre 2018
Andrew Morgan - January 2017
“ About it being difficult to force good error
handling, errors not having stack traces
and error handling being too verbose. ”
Chris Siebenmann - August 2018
“ I continue to be irritated by how
opaque important Go errors are. I should
not have to do string comparisons to
discover that my network connection failed
due to 'host is unreachable'.”
37. Meetup Golang Milano - 27 Settembre 2018
Errors - 4 modi per gestirli (1 e 2)
func main() {
_, err := read(“data.txt”)
if err == io.EOF {
log.Fatal(err)
}
}
func main() {
// With assertion.
err, ok := err.(*model.MissingError)
// Or type switch.
switch t := err.(type) {
default:
fmt.Println("not a missing error")
case *ModelMissingError:
fmt.Println("ModelMissingError", t)
}
}
1 sentinel error 2 error type check
⚠ Molto specifico! ⚠ Switch complessi o asserzioni sbagliate!
39. Obiettivi per Go 2
Errors - Obiettivi 1/3
Meetup Golang Milano - 27 Settembre 2018
- Ispezione dei programmi più agile e
meno prona agli errori
Cercando soluzioni per ispezionare gli
errori.
40. Obiettivi per Go 2
Errors - Obiettivi 2/3
Meetup Golang Milano - 27 Settembre 2018
- Risolvere il problema dei wrapper:
stampare gli errori con tutti i dettagli in
una formattazione standard:
consistente, ordinata, dettagliata,
localizzata e pulita.
41. Obiettivi per Go 2
Errors - Obiettivi 3/3
Meetup Golang Milano - 27 Settembre 2018
Ricordandosi i vincoli!
il codice attuale deve rimanere valido.
In più deve essere efficiente la creazione.
Ne vengono generati continuamente!
42. Errors - Ispezione
package errors
// A Wrapper is an error implementation
// wrapping context around another error.
type Wrapper interface {
// Unwrap returns the next error in the error chain.
// If there is no next error, Unwrap returns nil.
Unwrap() error
}
Interfaccia opzionale di wrap degli errori:
Meetup Golang Milano - 27 Settembre 2018
43. Errors - Ispezione
// instead of err == io.ErrUnexpectedEOF
if errors.Is(err, io.ErrUnexpectedEOF) { ... }
// instead of pe, ok := err.(*os.PathError)
if pe, ok := errors.As(*os.PathError)(err); ok
{ ... pe.Path ... }
Wrapper uccide “==“ e “type comparison” per errori di tipo 1,2,3
errors.Is
Meetup Golang Milano - 27 Settembre 2018
errors.As
44. Errors - Formattazione
package errors
// A Formatter formats error messages.
type Formatter interface {
// Format is implemented by errors to print a single error message.
// It should return the next error in the error chain, if any.
Format(p Printer) (next error)
}
// A Printer creates formatted error messages.
type Printer interface {
Print(args ...interface{})
Printf(format string, args ...interface{})
// Detail reports whether error detail is requested.
Detail() bool
}
Interfaccia implementata da errors:
Meetup Golang Milano - 27 Settembre 2018
Formattazione
Dettagli e
localizzazione
45. Meetup Golang Milano - 27 Settembre 2018
Errors - Formattazione - Prima e dopo
Error:
write users database: call myserver.Method:
dial myserver:3333: open /etc/resolv.conf:
permission denied
Error:
write users database:
more detail here
/path/to/database.go:111
--- call myserver.Method:
/path/to/grpc.go:222
--- dial myserver:3333:
/path/to/net/dial.go:333
--- open /etc/resolv.conf:
/path/to/os/open.go:444
--- permission denied
Go 1.11 Go 2
46. Errors - Critiche e domande
Meetup Golang Milano - 27 Settembre 2018
! E il costo di tutto questo? Microbenchmarks
! “Unwrap” non è così esplicativo, la libreria Dave
Cheney pkg/errors usa la parola “Cause”
! Non si complica la vita? Sì del programmatore,
no del programma?
Fonti: https://github.com/golang/go/wiki/
Go2ErrorValuesFeedback (14 contributi)
49. Experience reports on Generics
Generics - Experience Reports
Meetup Golang Milano - 27 Settembre 2018
22
50. Experience reports on Generics
Generics - Experience Reports
Meetup Golang Milano - 27 Settembre 2018
Chewxy - September 2017
“ Lack of generics and how it affects
building high performance multidimensional
arrays for different data types ”
Jon Calhoun - May 2017
“ Using code generation to survive
without generics in Go.”
51. Experience reports on Generics
Generics - Experience Reports
Meetup Golang Milano - 27 Settembre 2018
Chewxy - September 2017
“ Lack of generics and how it affects
building high performance multidimensional
arrays for different data types ”
Jon Calhoun - May 2017
“ Using code generation to survive
without generics in Go.”
r3vit - September 2018
“ E mo’ come la implemento questa
coda di strutture diverse senza i generics?”
52. Soluzioni a problemi quotidiani
Generics - Cosa sono
Meetup Golang Milano - 27 Settembre 2018
Nasce dall’idea di astrazione dal concreto.
Generalizzo strutture dati, funzioni, modellazione di
dominii (frameworks).
Sets, Trees, Matrix, Graphs, Hash-Tables, Queues…
53. PRO
Generics - Pro e Contro
Meetup Golang Milano - 27 Settembre 2018
- Veloci (per noi)
- Non devo reimplementare strutture
- Type-safety at compile time! (con limitazioni)
- Riuso del codice
- Generalizzo codice già scritto
CONTRO
- Tendono ad accumulare funzionalità: compile
time più lungo e codice “sporco”
- L’astrazione può imporre generalizzazioni
troppo “generiche”
- Ottimizzo di meno perché devo generalizzare di
più
- Complesse da implementare in maniera
soddisfacente
54. The generics dilemma (Russ Cox, 2009)
Generics - Dilemma
Meetup Golang Milano - 27 Settembre 2018
Do you want slow programmers,
slow compilers and bloated binaries,
or slow execution times?
55. Alternative ai Generics
Generics - Alternative
Meetup Golang Milano - 27 Settembre 2018
Copy &
paste code
Usare le
interfacce
Usare reflectCode
generators
56. Alternative ai Generics
Generics - Alternative
Meetup Golang Milano - 27 Settembre 2018
Introduce type-casting
(possibili errori), overhead
di spazio e il codice è più
lento di quelle specializzare
Overhead di spazio e il
codice è più lento di quelle
specializzare. Inoltre non è
così banale.
duplicazione di codice
e diversi generatori tra
cui scegliere (genny)
Copy &
paste code
Usare le
interfacce
Usare reflectCode
generators
57. Generics - Proposal
contract Addable(t T) {
t + t
}
func Sum(type T Addable)(x []T) T {
var total T
for _, v := range x {
total += v
}
return total
}
var x []int
intSum := Sum(int) // intSum has type func([]int) int
total := intSum(x)
Types and Contracts
Meetup Golang Milano - 27 Settembre 2018
Generic types
and
Contracts
58. Obiettivi per Go 2
Generics - Obiettivi
Meetup Golang Milano - 27 Settembre 2018
- Manipolare qualunque tipo di mappe o
channels e idealmente scrivere
funzioni polimorfiche (es: che possono
trattare valori sia []byte che string )
59. Generics - Critiche e domande
Meetup Golang Milano - 27 Settembre 2018
! Perché introdurre complessità?
! Non è così utile, potevo usare interfaces
! “Hard to read syntax” Roberto (empijei) Clapis - 2018
! E se fosse solo un problema di sintassi? Dave Cheney - 2018
Fonti: https://github.com/golang/go/wiki/Go2GenericsFeedback
(38 contributi + commenti)
e un Live Document! https://docs.google.com/document/d/
1vrAy9gMpMoS3uaVphB32uVXX4pi-HnNjkMEgyAHX4N4/edit#
63. Bonus! - Riassunto
Meetup Golang Milano - 27 Settembre 2018
- Go2 è in fase “bozza” ma si avvicina come 1.X
- Il processo è chiaro e lineare
- La community ha un ruolo importante
- Sono aperti numerosi fronti di evoluzione, tra cui:
- Error Handling (check/handle, try/catch?)
- Errors (Wrappers & Co.)
- Generics (o forse è meglio una alternativa?)
64. Russ Cox
We invite everyone in the
Go community to learn
more about the designs
and help us improve them.