-
Notifications
You must be signed in to change notification settings - Fork 0
/
golang.slide
1382 lines (832 loc) · 21.4 KB
/
golang.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
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
Go Language
Sep 2013
Giacomo Tartari
PhD student, University of Tromsø
* Go lecture 1/2
Introduction
Motivation
Syntax
Capabilities
Example code
* Go lectures 2/2
Practicalities
Installation
Environment
Tooling
HowTos
Demo?
* Go
* A new language?
Why?
and what for?
Don't we have Java?
C?
C++?
C#?
D?
Haskell?
Scala?
Python?
PHP?
Ruby?
Perl?!
Brainfuck!!!!
[add random language here]?
* A new language
What's wrong with all of the above?
.link http://talks.golang.org/2012/splash.article Rob Pike's take (one of the Go instigator)
Languages used at Google were not satisfactory
- These languages were developed before the multi-core revolution
- Millions of lines of code maintained by thousands of programmers
- Build times of many minutes or hours
* Go
Modern and pragmatical language
Not a research language to explore new horizons
A language to get the job done
Designed by and for people who build and maintain large systems
Easy to read, clean syntax
Good tools
Nothing exactly new but a collection of good features
* Go
Opensourced in 2009
Current version 1.1.2
As of 1/11/2013 feature freeze for Go 1.2
.image gopher.jpeg
* Go
C-like syntax
Compiled to machine code
CSP-like Concurrency
Garbage collected
Static and strong typed
No exceptions for handling errors
No inheritance but composition
No generics
No header files
.link http://golang.org/doc/faq
* Go benchmarks (!)
.image govsc.png 480 768
.link http://benchmarksgame.alioth.debian.org/u64q/go.php Benchmarks from here
* Go benchmarks (!)
.image govsjava.png 480 768
* Go benchmarks (!)
.image govspy.png 480 768
* Go benchmarks (!)
.image govsruby.png 480 768
* Hello World
.play hello.go /START/,/STOP/
#* Package
#
#.code hello.go /START/,/STOP/ HLpackage
#
#Go packages mix the properties of libraries, name spaces, and modules
#
#A package is compiled in a static library or in a (statically linked) executable if `main.main()` is present
#
#Multiple files can be part of a package
#
#No restriction to what can be in a file (unlike Java)
#
#
#
#
#* Importing other packages
#
#.code hello.go /START/,/STOP/ HLimport
#
#Import statements are path to the package binary and/or source code
#
#e.g.
#
#- import "encoding/json"
#- import "net/http/cookiejar"
#- import "github.com/golang/groupcache"
#- import "code.google.com/p/go.talks/pkg/present"
#
#
#
#* Function declaration
#
#.code hello.go /START/,/STOP/ HLmain
#
#The func keyword is used to declare/define a function
#
# func Println(a ...interface{}) (n int, err error)
#
#Functions are first-class
#
#Functions can have more than one return value
##
##.code hello.go /STARTF/,/STOPF/ HLmain
#
##Idiomatic code often looks like:
#
##`func` `fname(param)(stuff,` `error){...}`
#
#
#
#* Output
#
#.code hello.go /START/,/STOP/ HLfunc
#
#From golang.org/pkg/fmt/
#
# func Fprint(w io.Writer, a ...interface{}) (n int, err error)
# func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error)
# func Fprintln(w io.Writer, a ...interface{}) (n int, err error)
# ...
# func Print(a ...interface{}) (n int, err error)
# func Printf(format string, a ...interface{}) (n int, err error)
# func Println(a ...interface{}) (n int, err error)
# func Scan(a ...interface{}) (n int, err error)
# func Scanf(format string, a ...interface{}) (n int, err error)
# func Scanln(a ...interface{}) (n int, err error)
# func Sprint(a ...interface{}) string
# func Sscan(str string, a ...interface{}) (n int, err error)
# ...
* Basic types
bool
string
int int8 int16 int32 int64
uint uint8 uint16 uint32 uint64 uintptr
byte // alias for uint8
rune // alias for int32
// represents a Unicode code point
float32 float64
complex64 complex128
Also array, slice, maps and channels
But we'll see them later
* Some operators
+ sum integers, floats, complex values, strings
- difference integers, floats, complex values
* product integers, floats, complex values
/ quotient integers, floats, complex values
% remainder integers
&& conditional AND p && q is "if p then q else false"
|| conditional OR p || q is "if p then true else q"
! NOT !p is "not p"
== equal
!= not equal
< less
<= less or equal
> greater
>= greater or equal
&x address operator
*p pointer indirection
#* Pointers
No pointer arithmetics
* Packages
- Go packages mix the properties of libraries, name spaces, and modules
- A package is compiled in a static library or in a (statically linked) executable if `main.main()` is present
- Multiple files can be part of a package
- No restriction to what can be in a file
- Name visibility outside packages is a property of the name
* Packages, exported identifiers
package mypackage
import (
"errors"
"fmt"
"github.com/user/package"
)
var A int //exported
func MyFunc(){...} //exported
var b float32 //not exported
A name is visible outside its package iff
- The first character of the identifier's name is upper case
- The identifier is declared in the package block or it is a field name or method name.
Remember `fmt.Println(...)` in hello world?
* Variables and Constants
var (
B string = "hello"
x, y, z float32
p *int
)
const (
C = iota //0
D //1
E //2
)
As imports variables and constants can be declared in blocks
Variables, and constants, can be initialized when declared
Together with the iota constant generator it permits light-weight declaration of sequential values
#
#
#* Enums? Almost
# type ByteSize float64
#
# const (
# _ = iota // ignore first value by assigning to blank identifier
# KB ByteSize = 1 << (10 * iota)
# MB
# GB
# TB
# PB
# EB
# ZB
# YB
# )
#The blank identifier ( _ ) may be used in a declaration but the declaration does not introduce a new binding
#
* More variables
Unused variables (and imports) are errors in Go
The blank identifier ( _ ) may be used in a declaration but the declaration does not introduce a new binding
Or in an assignment but the value is discarded
_, _, _ = x, y, z
const (
_ = iota //0
A //1
B //2
)
* More variables
Inside functions variable can be defined with `:=`
x := SomeFunc()
y := x++
x, y, z := 0, 1, 2
The compiler infers the type
.image gopher2.jpeg
* Functions
- First class functions
- Higher order functions
- User defined function types
- Function literals
- Closures
- Multiple return values
* Named return values
.play funcdiv.go /START/,/STOP/
Return parameters can be named and treated as variables
A return statement without arguments returns the current values of the results
* More functions
First-class functions, higher-order functions and user-defined function types
.play firstfunc.go
* More functions
Function literals are closures
.play closures.go
* Deferred functions
A defer statement schedules a function call to be run just before the function executing the defer returns
The canonical examples are unlocking a mutex or closing a file
package main
import (
"fmt"
"os"
)
func main() {
fname := "/tmp/file.tmp"
f, err := os.Open(fname)
if err != nil {
/*handle error*/
}
defer f.Close()
// do stuff with file
}
* Types, allocations and composition
- Type definition
- Method definition
- Allocation
- Interfaces
- Composition and embedding
.image gopher3.jpeg
* Type definition
type MyInt int
type Vertex struct{
X, Y int
}
type Writer interface{
Write()
}
type Callback func(*int, string)
Go is strong typed so `MyInt` is not an `int`
Types can be converted with this syntax `int(MyInt)`
Any type can have methods (even functions)
* Allocation
Struct literals
var (
p = Vertex{1, 2} // has type Vertex
q = &Vertex{1, 2} // has type *Vertex
r = Vertex{X: 1} // Y:0 is implicit
s = Vertex{} // X:0 and Y:0
t = Vertex{X: 3, Y: 4}
)
Built in function `new()` returns a pointer to a newly allocated and zeroed memory
v := new(Vertex) // has type *Vertex
Built in function `make()` used to allocate built in types: channels, maps and slices
m := make(map[string]int)
* Method
func (v1 Vertex)Add(v2 Vertex)Vertex{
return Vertex{v1.X + v2.X, v1.Y + v2.Y}
}
func (v *Vertex)Sum(a Vertex) {
v.X += a.X
v.Y += a.Y
}
Method receivers and method sets
Vertex
- Add(Vertex)
*Vertex
- Add(Vertex)
- Sum(Vertex)
* Method receivers
.play receiver.go /START/,/STOP/
_If_x_is_addressable_and_&x's_method_set_contains_m,_x.m()_is_shorthand_for_(&x).m()_
* Interfaces
Interfaces are a sets of methods
Just behavior
Often just a few methods
From pkg/io
type Writer interface {
Write(p []byte) (n int, err error)
}
type Reader interface {
Read(p []byte) (n int, err error)
}
type Closer interface {
Close() error
}
* Interfaces
An interface is satisfied if the type implements all the methods in the set
No _implements_ keyword
Interface satisfaction is statically checked at compile time
Interfaces are type-safe
Structural typing, is like duck typing but better
The compiler tells you if it is a _duck_
* Interfaces
Any type satisfies the empty method set
interface{}
.play iempty.go
* Method sets
N.B.
.play interfset.go /START/,/STOP/
_The_concrete_value_stored_in_an_interface_is_not_addressable_
* Interfaces composition
Interfaces can be composed
From pkg/io
type ReadWriteCloser interface {
Reader
Writer
Closer
}
func MyFunc(stream io.ReadWriteCloser) error{
...
stream.Read()
sream.Write(data)
stream.Close()
...
}
* Type assertion
type error interface {
Error() string
}
type PathError struct{
Path string
Ctx *Context
Timestamp time.Time
}
func (pe PathError) Error() string{
return fmt.Sprintf("Wrong path: %s", pe.Path)
}
err := FuncPath(...)
ep, ok := err.(PathError)
if ok{
ep.Ctx
}
* Struct embedding
Also struct can be composed by embedding
.play embed.go
* Struct embedding
And the interface they are satisfying as well
type Locker interface {
Lock()
Unlock()
}
import "sync"
type Vertex struct {
X, Y int
}
type VertexLocker struct{
sync.Mutex
Vertex
}
vl := VertexLocker{}
vl.Lock()
vl.X = 99
vl.Unlock()
* Flow Control: if, for and switch
#intermezzo reflection
#type switch
* If
.play if.go
* For
.play for.go
As in C or Java, you can leave the pre and post statements empty
And drop the semicolons: C's while is spelled for in Go
#* Switch
#
#.play switch.go
#
* Switch
Not just numbers
.play switchstring.go
* Type switch
What is the actual type of an interface?
err := json.Unmarshal(data, &p)
if err != nil {
switch t := err.(type) {
case *json.UnmarshalFieldError:
log.Println(t)
case *json.UnmarshalTypeError:
log.Println(t)
case *json.UnsupportedTypeError:
log.Println(t)
case *json.UnsupportedValueError:
log.Println(t)
case *json.SyntaxError:
log.Println(t)
case *json.InvalidUnmarshalError:
log.Println(t)
}
return err
}
* Arrays, slices and maps
#and channels
* Arrays
.play array.go
* Arrays
Value type not reference type
The size of an array is part of its type
.play array2.go
* Slices
.play slice.go
Just a *slice* of an array
* Slice internals
.image godata3.png
.play slice2.go
* Slice built in functions
Append to a slice
func append(slice []Type, elems ...Type) []Type
Slice capacity
func cap(v Type) int
Slice length
func len(v Type) int
Copy a slice
func copy(dst, src []Type) int
* Slice tricks
Append
a = append(a, b...)
Copy
b = make([]T, len(a))
copy(b, a)
Cut
a = append(a[:i], a[j:]...)
Delete
a = append(a[:i], a[i+1:]...)
// or
a = a[:i+copy(a[i:], a[i+1:])]
//without preserving order
a[i], a = a[len(a)-1], a[:len(a)-1]
etc...
* Maps
.play maps.go /START/,/STOP/
Keys can be integers, floats, complex, strings, pointers, interfaces, structs, arrays
* Range
.play range.go
* Concurrency: goroutines and channels
* Concurrency vs Parallelism
.link http://concur.rspace.googlecode.com/hg/talk/concur.html#title-slide
- Concurrency != parallelism
- Concurrency is the composition of independently executing processes
- Concurrency enables parallelism
- Concurrency is about structure
- Parallelism is about execution
- A concurrent program can be executed correctly on one CPU
* Goroutine
.play goroutine.go
#We can use the sync package, but we have something better...
* Concurrency
Goroutines provide concurrency
- `go` statement allows us to run functions independently in different goroutines
- Goroutines live in the same address space
- Think of them as a very lightweight threads
Now we need to communicate
- We need return values form the goroutines
- We need to feed fresh data to the goroutines to be elaborated
* Communication
Same address space you say?
Synchronize access to shared memory
- Fence some sheared memory with mutex, locks, conditions...
- Communicate by reading/writing this shared memory
We can do better, we have channels!!
* Channels
Channels can _connect_ goroutines and allow them to communicate
The go runtime will take care of the synchronization details
We just care about sending and receiving data
_Don't_communicate_by_sharing_memory;_share_memory_by_communicating._
* Channels
ch := make(chan int) // unbuffered channel
ch := make(chan int, 10) // buffered channel
Unbuffered channels combine communication with synchronization
Buffered channel are more like synchronized and type safe FIFO queues
Communication primitives
ch <- v // Send v to channel ch
v := <-ch // Receive from ch, and assign value to v
Both operation are blocking if the channel is not ready to communicate
Same as Unix pipes
- Read blocks while pipe is empty
- Write blocks while pipe is full
* Communication
.code concur.go /STARTPING/,/STOPPONG/
* Communication
.play concur.go /STARTMAIN/,/STOPMAIN/
The computation happens in the goroutines
The value is passed back and forth
The communication is the synchronization
* Sharing is caring
Memory is not fenced by locks and condition
Memory is shared bu _passing_ it along
After you give it away is not your memory anymore
.image gopher2.jpeg
* More channels
Channels can be closed to signal the receivers the termination of the data flow
ch := make(chan int)
close(ch)
To check if a channel is closed use the multi-valued assignment form of the receive operator
x, ok := <-ch
if !ok{
fmt.Println("Channel closed!")
}
Receiving from a closed channel always succeeds, immediately returning the element type's zero value
* Range in channels
.play rangechan.go
Range will iterate on all the values sent through the channel until it is closed
Closing a non empty channel will not prevent us from receiving the already sent values
What if we do not close the channel?
* Select
Select is similar to switch but each case is a communication statement
in := make(chan int)
out := make(chan int)
select{
case i := <- in:
fmt.Println("received i")
case out <- x:
fmt.Println("sent x")
default:
fmt.Println("no communication")
}
If `default` case is not present `select` blocks until a channel is ready to communicate
`select{}` blocks forever
* Select
.play select.go /START/,/STOP/
* Timeouts
timeout := time.After(100 * time.Millisecond)
select {