-
Notifications
You must be signed in to change notification settings - Fork 0
/
features.slide
683 lines (438 loc) · 19.2 KB
/
features.slide
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
Go is Different
"90% Perfect, 100% of the Time"
28 Aug 2018
Tahir Hashmi
@code_martial
* Quick Examples
* Hello World
.play -numbers features/hello.go
- Stand-alone functions, of course. Who disallows those?
- Short variable declaration ( `:=` ) infers type from RHS
- Go source is UTF-8 by specification
- Hit the "Run" button to execute the code above
* Fibonacci
.play -numbers features/fib.go
- Closures, FTW!
- Buggy implementation. I deferred the fix.
* Fibonacci Redux
.play -numbers -edit features/fib-defer.go /^func/,/OMIT$/
- `defer` to execute something before exiting the function
- Like Java `finally` but not limited to "exceptions"
- Lambdas, FTW!
* Quicksort
.play -numbers features/quicksort.go /^var input/,/^}/
- `[]Foo` is a "slice" of type `Foo`. Contiguous, growable, random-access sequence
- `[start:end]` to "reslice". Underlying sequence not copied while reslicing
* Parallel Quicksort
.play -numbers features/parallel-quicksort.go /^func quicksort/,/^}/
- Any ol' function/method can be called asynchronously.
- Use channels (`chan`) to co-ordinate flow, if needed
* Syntax
* Syntax is not important...
- unless you're programming
- or writing tools
Tooling is essential, so Go has a clean syntax.
Not super small, just clean:
- mostly regular context-free grammar
- only 25 keywords
- straightforward to parse (no type-specific context required)
- easy to predict, reason about
.caption [[http://talks.golang.org/2012/splash.slide]]
* Declarations
Uses Pascal/Modula-style syntax: name before type, more type keywords.
var fn func([]int) int
type T struct { a, b int }
not
int (*fn)(int[]);
struct T { int a, b; }
Easier to parse—no symbol table needed. Tools become easier to write.
One nice effect: can drop `var` and derive type of variable from expression:
var buf *bytes.Buffer = bytes.NewBuffer(x) // explicit
buf := bytes.NewBuffer(x) // derived
For more information: [[http://golang.org/s/decl-syntax]]
.caption [[http://talks.golang.org/2012/splash.slide]]
* Function syntax
Function on type `T`:
func Abs(t T) float64
Method of type `T`:
func (t T) Abs() float64
Variable (closure) of type `T`:
negAbs := func(t T) float64 { return -Abs(t) }
In Go, functions can return multiple values. Common case: `error`.
func ReadByte() (c byte, err error)
c, err := ReadByte()
if err != nil { ... }
More about errors later.
.caption [[http://talks.golang.org/2012/splash.slide]]
* No default arguments
Go does not support default function arguments.
Why not?
- too easy to throw in defaulted args to fix design problems
- encourages too many args
- too hard to understand the effect of the fn for different combinations of args
Extra verbosity may happen but that encourages extra thought about names.
Related: Go has easy-to-use, type-safe support for variadic functions.
.caption [[http://talks.golang.org/2012/splash.slide]]
* Export syntax
Simple rule:
- upper case initial letter: `Name` is visible to clients of package
- otherwise: `name` (or `_Name`) is not visible to clients of package
Applies to variables, types, functions, methods, constants, fields....
That Is It.
Not an easy decision.
One of the most important things about the language.
Can see the visibility of an identifier without discovering the declaration.
Clarity.
.caption [[http://talks.golang.org/2012/splash.slide]]
* Packages and Scope
*
Go has very simple scope hierarchy:
- universe
- package
- file (for imports only)
- function
- block
.caption [[http://talks.golang.org/2012/splash.slide]]
* Locality of naming
Nuances:
- no implicit `this` in methods (receiver is explicit); always see `rcvr.Field`
- package qualifier always present for imported names
- (first component of) every name is always declared in current package
No surprises when importing:
- adding an exported name to my package cannot break your package!
Names do not leak across boundaries.
In C, C++, Java the name `y` could refer to anything
In Go, `y` (or even `Y`) is always defined within the package.
In Go, `x.Y` is clear: find `x` locally, `Y` belongs to it.
.caption [[http://talks.golang.org/2012/splash.slide]]
* Function and method lookup
- Method lookup by name only, not type.
- A type cannot have two methods with the same name, ever.
- Easy to identify which function/method is referred to.
- Simple implementation, simpler program, fewer surprises.
Given a method `x.M`, there's only ever one `M` associated with `x`.
.caption [[http://talks.golang.org/2012/splash.slide]]
* Packages
Every Go source file, e.g. `"encoding/json/json.go"`, starts
package json
where `json` is the "package name", an identifier.
Package names are usually concise.
To use a package, need to identify it by path:
import "encoding/json"
And then the package name is used to qualify items from package:
var dec = json.NewDecoder(reader)
Clarity: can always tell if name is local to package from its syntax: `Name` vs. `pkg.Name`.
Package combines properties of library, name space, and module.
.caption [[http://talks.golang.org/2012/splash.slide]]
* Package paths are unique, package names are not
The path is `"encoding/json"` but the package name is `json`.
The path identifies the package and must be unique.
Project or company name at root of name space.
import "google/base/go/log"
Package name might not be unique; can be overridden. These are both `package`log`:
import "log" // Standard package
import googlelog "google/base/go/log" // Google-specific package
Every company might have its own `log` package; no need to make the package name unique.
Another: there are many `server` packages in Google's code base.
.caption [[http://talks.golang.org/2012/splash.slide]]
* Remote packages
Package path syntax works with remote repositories.
The import path is just a string.
Can be a file, can be a URL:
go get github.com/4ad/doozer // Command to fetch package
import "github.com/4ad/doozer" // Doozer client's import statement
var client doozer.Conn // Client's use of package
.caption [[http://talks.golang.org/2012/splash.slide]]
* Dependencies
Dependencies are defined (syntactically) in the language.
Explicit, clear, computable.
import "encoding/json"
Unused dependencies cause error at compile time.
Efficient: dependencies traversed once per source file...
.caption [[http://talks.golang.org/2012/splash.slide]]
* No circular imports
Circular imports are illegal in Go.
The big picture in a nutshell:
- occasional minor pain,
- but great reduction in annoyance overall
- structural typing makes it less important than with type hierarchies
- keeps us honest!
Forces clear demarcation between packages.
Simplifies compilation, linking, initialization.
.caption [[http://talks.golang.org/2012/splash.slide]]
* Error Handling
* The "error" Type
type error interface {
Error() string
}
- Pre-declared identifier, `error` is always in scope. No import needed.
- Use `errors.New()` or `fmt.Errorf()` functions to create new error values
* Functions Return Data + Errors
func (t T) DoSomething(...) (r ReturnType, error)
- Functions can return multiple values
- Errors are values
- ∴ Functions can always return errors alongside actual return values
- Errors can carry rich context
- Custom error types are easy
* Exception Handling Bugbears
try {
Foo foo = something.returnAFoo()
Bar bar = otherthing.returnABar()
executor.doSomething()
} catch(Exception e) {
log.Error("Boo-boo happened", e.toString())
rethrow
}
- Can't guess which lines in `try` block can throw exceptions
- Only one exception handled per `try-catch` block (bad for validators, etc.)
- Mixing of expected and exceptional... exceptions
- Branching of execution path – exception flow separate from non-exceptional flow
- Top-level catch-all to prevent program crash
* Error Handling in Go
if err := json.Unmarshal([]byte(expected), &expectedObj); err != nil {
t.Fatal("Fix this unit test. Error: ", err, expected)
}
responseObj = make(responseT, 0)
if err := json.Unmarshal(response[20:], &responseObj); err != nil {
t.Error("Could not JSON Decode Response. Error: ", err)
}
- In-line error checking leads to contextual handling
- Compiler disallows ignoring error while receiving return values from functions
.play features/error-skip.go /START/,/END/
* defer, panic and recover
* defer
A *defer*statement* pushes a function call onto a stack (LIFO)
The saved call is executed immediately after the surrounding function returns
Usually used to perform clean-ups (closing open files, unlocking mutexes, etc)
Like Java `finally` but not just for exceptions.
Like C++ destructors but not just at end of lifetime
*Syntax*
DoSomething() // Regular fn. call
defer DoSomething() // Deferred fn. call
* Rules of deferred execution
1. Arguments of deferred functions are evaluated when `defer` statement is evaluated
.play features/defer-eval.go /^func a/,/^}/
2. Multiple deferred functions are called in LIFO order
.play features/defer-lifo.go /^func a/,/^}/
3. Deferred functions can access and modify surrounding function's return vars
.play features/defer-return.go /^func a/,/^}/
* panic
- `panic()` is like `throw` from C++/Java
- Unwinds the call stack until "recovered" or the carrying goroutine's boundary is reached
- Parent goroutines can't recover panics from child goroutines
- Unrecovered panics cause the program to crash when they hit the goroutine boundary
.play features/panic.go
* recover
- `recover()` is used to detect a panic.
- It is useful only as a deferred function. Example:
.play features/recover.go
* When to Panic
Panic only when:
- There is an error condition that can't be caught at compile time, and...
- ... the condition only arises due to buggy code. (e.g. Indexing a `nil` slice)
Also,
- panic inside a deep recursion (e.g. LR parsing) to break out to the top level
- recover the panic and convert it into an error for callers of the recursive function.
* Concurrency Primitives
*
Excellent introduction by Rob Pike:
[[http://talks.golang.org/2012/concurrency.slide][Go Concurrency Patterns]]
Please go through it before moving ahead!
* Container Types
* Arrays
Generic fixed capacity homogenous sequence
arr := [5]int // Array of 5 integers
*Slices*
Generic variable capacity homogenous sequence
slc := make([]int) // 0 element slice of integers
slc := []int{} // Initializer syntax
slc := make([]int, 5) // 5 element slice of integers
slc := []int{1, 2, 3, 4} // Short declaration and initialization
slc := make([]int, 5, 10) // slice with capacity of 10
l, c := len(slc), cap(slc) // find length and capacity
lo,hi := 1,3
rsl := slc[lo:hi] // New slice with elements between lo and hi positions only
Arrays and Slices are bounds checked. Indexing out of bounds causes a panic.
* Maps
Generic hash-table of key-value pairs of homogenous types
.play features/maps.go /^ /,/OMIT$/
* Considerations
- Maps, Slices and Arrays are not synchronised
- Maps can re-order entries on every insertion/deletion
- Successive map iterations can yield keys in different order
- Simple container assignment or reslicing does not copy underlying storage
- Use `copy()` built-in for deep copying arrays/slices (not maps)
.play features/slice-copy.go /^func/,/^}/
* Structs and Methods
* Struct
- C-like composite type
- Zero initialised on declaration
.play features/struct.go /^type/,/OMIT$/
* Methods (functions bound to a struct)
.play features/method.go /^\//,/OMIT$/
* Pointer Receiver
.play features/pointer-receiver.go /^func/,/OMIT$/
* Everything is Pass by Value
.play features/pass-by-value.go /^func/,/OMIT$/
These semantics apply to stand-alone functions too
* Type Composition
* Form A Whole By Arranging Parts
- A struct can have one or more types as its _parts_
type Person struct {
id uint64
}
type Authorization struct {
accessTok string
}
type Player { // Structurally equivalent to the previous 'Player' type
Person // 'id' field embedded from Person
Stamina int `json:"stam"`
Health int `json:"health"`
Authorization // 'accessTok' field embedded from Authorization
}
- Anonymous Fields/Methods of the parts get "promoted" to the _whole_
Player.id // refers to Person.id as embedded inside Player
* Rules of Embedding
type T struct {
f Foo
}
type C struct {
b Bar
}
type S struct {
T // A struct field declarted with a type but no field name is an
*C // anonymous/embedded field. T and *C are embedded fields of type S
}
- An embedded field must be a type `T`, or...
- ... a pointer to non-interface type `C`, and...
- ... `C` itself may not be a pointer to any other type
* Field Promotion
type ( T struct { f Foo }; C struct { b Bar } )
type S struct {
T // A struct field declarted with a type but no field name is an
*C // anonymous/embedded field. Here, T and *C are embedded fields of type S
}
- Fields of `T` and `C` get promoted to S (e.g. `T.f` gets exposed as `S.f` above)
- The method sets of `S/*S` include promoted methods with receiver `T`
- The method sets of `S/*S` include promoted methods with receiver `C` or `*C`
- Ambiguity in field name resolution causes promotion to fail, needs explicit reference
- Field promotion is transitive
- Promoted fields can't be used in composite literal notation for the struct
s := S{f: foo} // invalid
s := S{}; s.f = foo // valid
s := S{T{f:foo}, nil} // valid
* Composition is Not Inheritance
.play features/composition-not-inheritance.go /^type/,/OMIT$/
What Happened Here?
* `this` is misleading
.play features/composition-not-inheritance-2.go /^type/,/OMIT$/
Now you know why not to write `this` or `self` in Go. Because, clarity.
* Interfaces
* Aside: Being Object Oriented
Go has
- No implementation inheritance.
- No subtype polymorphism.
- No parametric polymorphism (C++ Templates/Java Generics)
*Are*C++*and*Java*Object*Oriented?*
- _"I_made_up_the_term_object-oriented,_and_I_can_tell_you_I_did_not_have_C++_in_mind."_ – Alan Kay [[https://youtu.be/oKg1hTOQXoY?t=10m34s][#]]
- _"The_big_idea_is_"messaging"_[between_objects]_-_that_is_what_the_kernel_of_Smalltalk/Squeak_is_all_about"_ – Alan Kay [[http://c2.com/cgi/wiki?AlanKayOnMessaging][#]]
- _"Yes_–_[delegation]_without_an_inheritance_hierarchy._Rather_than_subclassing,_just_use_pure_interfaces."_ – James Gosling on recreating Java differently. [[http://www.artima.com/intv/gosling34.html][#]]
* Interfaces: the Go way
Go interfaces are small.
type Stringer interface {
String() string
}
A `Stringer` can pretty print itself.
Anything that implements `String` is a `Stringer`.
No explicit `implements` declaration required.
.caption Source [[https://talks.golang.org/2014/go4gophers.slide]]
* An interface example
An `io.Reader` value emits a stream of binary data.
type Reader interface {
Read([]byte) (int, error)
}
ByteReader implements an io.Reader that emits a stream of its byte value.
.code go4gophers/reader.go /ByteReader/,/^}/
.caption Source [[https://talks.golang.org/2014/go4gophers.slide]]
* Wrapping interfaces
.code go4gophers/reader.go /LogReader/,/STOP/
Wrapping a `ByteReader` with a `LogReader`:
.play go4gophers/reader.go /START/,/STOP/
By wrapping we compose interface _values_.
.caption Source [[https://talks.golang.org/2014/go4gophers.slide]]
* Chaining interfaces
Wrapping wrappers to build chains:
.code go4gophers/chain.go /START/,/STOP/
More succinctly:
.play go4gophers/chain.go /LogReader{io/
Implement complex behavior by composing small pieces.
.caption Source [[https://talks.golang.org/2014/go4gophers.slide]]
* Programming with interfaces
Interfaces separate data from behavior.
With interfaces, functions can operate on _behavior:_
// Copy copies from src to dst until either EOF is reached
// on src or an error occurs. It returns the number of bytes
// copied and the first error encountered while copying, if any.
func Copy(dst Writer, src Reader) (written int64, err error) {
.play go4gophers/chain.go /LogReader{io/
`Copy` can't know about the underlying data structures.
.caption Source [[https://talks.golang.org/2014/go4gophers.slide]]
* A larger interface
`sort.Interface` describes the operations required to sort a collection:
type Interface interface {
Len() int
Less(i, j int) bool
Swap(i, j int)
}
`IntSlice` can sort a slice of ints:
type IntSlice []int
func (p IntSlice) Len() int { return len(p) }
func (p IntSlice) Less(i, j int) bool { return p[i] < p[j] }
func (p IntSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
`sort.Sort` can sort a `[]int` with `IntSlice`:
.play go4gophers/sort.go /START/,/STOP/
.caption Source [[https://talks.golang.org/2014/go4gophers.slide]]
* Another interface example
The `Organ` type describes a body part and can print itself:
.play go4gophers/organs.go /type Organ/,$
.caption Source [[https://talks.golang.org/2014/go4gophers.slide]]
* Sorting organs
The `Organs` type knows how to describe and mutate a slice of organs:
.code go4gophers/organs2.go /PART1/,/PART2/
The `ByName` and `ByWeight` types embed `Organs` to sort by different fields:
.code go4gophers/organs2.go /PART2/,/PART3/
With embedding we compose _types_.
.caption Source [[https://talks.golang.org/2014/go4gophers.slide]]
* Sorting organs (continued)
To sort a `[]*Organ`, wrap it with `ByName` or `ByWeight` and pass it to `sort.Sort`:
.play go4gophers/organs2.go /START/,/STOP/
.caption Source [[https://talks.golang.org/2014/go4gophers.slide]]
* Another wrapper
The `Reverse` function takes a `sort.Interface` and
returns a `sort.Interface` with an inverted `Less` method:
.code go4gophers/organs3.go /func Reverse/,$
To sort the organs in descending order, compose our sort types with `Reverse`:
.play go4gophers/organs3.go /START/,/STOP/
.caption Source [[https://talks.golang.org/2014/go4gophers.slide]]
* Generics?
_""Really_good_idea,_you_gotta_do_it_this_way"._But_they_[language_designers]_all_had_a_different_version_of_"this_way"._They_usually_had_two_"this_way"s."_ – James Gosling [[https://www.youtube.com/watch?v=9ei-rbULWoA&t=13m26s][#]]
Different Generics implementations make different trade-offs.
Go's designers do not want to choose a trade-off on users' behalf.
Go's features make generics usually unnecessary.
- `slice` and `map` provide built-in, composable, generic containers
- Interfaces allow writing generic algorithms, bound by behaviour
- Functions-as-values allow pluggable logic
- `go`generate` for code generation as in C++ Templates
* Summary
Go is Different
- Simplifies code layout
- Has few, but orthogonal features
- Provides powerful concurrency primitives
- Has built-in generic composable containers (`slice`, `map`)
- Closer to the original OOP architecture as developed in Smalltalk
- De-emphasizes type hierarchies in favour of composition and delegation
Less is More
* Take a tour of Go
[[http://tour.golang.org/]]
* Acknowledgement
Byline is the title of [[https://talks.golang.org/2014/gocon-tokyo.slide][a talk]] by Brad Fitzpatrick