-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgo-training.slide
2558 lines (1570 loc) · 58.4 KB
/
go-training.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
Learning go
November 4th, 2024
Tags: go golang xebia
Patrick Akil
Software engineer, Xebia
http://www.xebia.com/
https://github.com/PatAkil/
https://www.linkedin.com/in/patrick-akil-721b07105/
#----------------------------------------------
* About me
.image examples/images/microphone.JPG 305 456
- Fitness, Podcasting, Content creation
- IoT, Ecommerce, Health Tech
- Effectiveness: organisational, team and personal
- Running golang in production @Wavin, @Action, @Duxxie & more!
#----------------------------------------------
* About you
- Who are you?
- What are your expectations and goals?
#----------------------------------------------
* Your experience
- What programming languages?
- Go installed on your laptop?
- Written any go code?
- Completed "A tour of go"?
- Completed go tutorials? Read a book?
- Used go tool-chain? go get, go build, go install?
- json/xml marshalling?
- Built an http-client and http-server?
- Used channels and goroutines?
- Unit testing?
- Own open-source project? Production code?
#----------------------------------------------
* Housekeeping
#----------------------------------------------
* Overall agenda
Past
- Startup
- Basics (A Tour of Go)
Now
- Interfaces
- More on functions
- Testing
- Concurrency
- Generics
- & More!
#----------------------------------------------
* Approach
- Learn by example
- See code, run code
- Associate with something you already know
- Questions
- Feedback
#----------------------------------------------
* Language
#----------------------------------------------
* Why go was created?
- Help Google solve problems: handle web requests
- Simple: limited -> easy to read
- Scale: infrastructure, teams, code bases
- Compile, startup and run fast
- Safe and reliable
- Optimum between C++ and Python
Also works for us
.link https://bradfitz.com/2020/01/30/joining-tailscale
#----------------------------------------------
* Similarities with Java (or Kotlin)
- General purpose
- Curly-braced
- Typestrong
- Compiled
- Garbage collected
- Object oriented
- Performant
#----------------------------------------------
* Differences with Java
Missing in go:
- Constructors (but uses "constructor" functions)
- Inheritance (but has "embedding" to compose)
- Exceptions
- Annotations
- Mutability
Missing in java:
- Rich standard library and toolchain
- Built-in concurrency
#----------------------------------------------
* Sweetspot for go
- Serving the web
- Components that need to be fast and reliable
- High throughput and concurrency
- Serve spiky traffic (fast startup eases scaling up)
- Large scale (people, lifetime and size)
Guaranteed backwards compatability 🙌
#----------------------------------------------
* Summary of the language
- Keywords:
break case continue default defer else (fallthrough) for (goto) if return switch
package import func const interface map range struct type chan go select var
- Types:
error string rune bool byte int int8 int16 int32 int64 float32 float64
uint uint8 uint16 uint32 uint64 (uintptr) (complex64) (complex128)
- Constants:
true false iota
- Zero value:
nil
- Functions:
append cap close complex copy delete len make new (panic) (recover)
#----------------------------------------------
* Useful sources of information
.link https://go.dev
.link https://go.dev/tour
.link https://go.dev/doc/effective_go
.link https://golangweekly.com/ golangweekly.com/ (newsletter to keep up)
.link https://github.com/avelino/awesome-go
#----------------------------------------------
* Getting our hands dirty
#----------------------------------------------
#----------------------------------------------
#* Installation git and golang
#----------------------------------------------
#- Install git:
#.link https://git-scm.com/download
# $ brew install git # on mac
# $ from download # on windows
#- Install go:
#.link https://golang.org/doc/install#download
# $ brew install go # on mac
# $ sudo apt-get install golang # on linux
# $ from msi file to c:\Go # on windows
#----------------------------------------------
* Verify installation
#----------------------------------------------
Verify git:
$ git --version
Verify go:
$ go version
At least version go1.23
No output means something's missing!
#----------------------------------------------
#* More setup (macos, unix)
#- Make sure the directory of the "go"-executable is in the PATH env-var
# $ echo $PATH
# $ PATH=${PATH}:/usr/local/bin # in ~/.bash_profile
#- Make the directory of your self-made executables is in the PATH env-var
# $ export PATH=${PATH}:${HOME}/go/bin # in ~/.bash_profile
#----------------------------------------------
* Get the training material on your laptop
$ cd ${HOME} # on unix/mac
$ cd /d %USERPROFILE% # on windows
$ git clone https://github.com/xebia/go-training.git
Everything will end up in go-training:
go-training
├── go-training.slide
├── examples/
└── solutions/
Switch to this dir:
$ cd go-training
And build and install the training project
$ go install ./... # Results end up in ${HOME}/go/...
#----------------------------------------------
* Dev tools
- IntelliJ IDEA or Goland
- unix terminal or windows command
- git
PRO TIP:
- Format-on-save: Use "filewatcher"-plugin
# Use "filewatcher"-plugin with "goimports"
# $ go get -u golang.org/x/tools/cmd/goimports
#----------------------------------------------
* Run the interactive presentation locally
As described in the `goPresent.md`
$ go get golang.org/x/tools/cmd/present
$ go run golang.org/x/tools/cmd/present -http=:3999 -use_playground=true
The presentation should be available in your browser at:
.link http://127.0.0.1:3999
#----------------------------------------------
* First program
Note that many examples in the presentation are editable and executable (Run!)
.play -edit examples/first/first.go
Start using the go toolchain:
$ go fmt # standard formatter (goimports is even better)
$ go run first.go # compiles and runs right away
$ go build # creates executable "./first" or ./first.exe in .
$ go install # creates executable "first" in ${HOME}/go/bin
$ first # or ${HOME}/go/bin/first
Hi everybody!
#----------------------------------------------
* Exercise 1: Write, build and run your first program
Prepare dedicated directory for exercises:
$ mkdir -p exercises # base directory for all exercises
$ cd exercises
$ mkdir -p first # dir for this exercise
$ cd first
Tasks:
- Create a file first.go
- Write
- Compile
- Format
- Install
- Run
Peek: examples/first/first.go
#----------------------------------------------
* Where do the executables end up?
- "Workspace"
${HOME}/go # on unix
%HOMEPATH%/go # on windows
$env:GOPATH # on powershell
- Contains all go stuff
Convention:
${HOME}/go
├── pkg/ # libraries
└── bin/ # executables
- The toolchain uses these conventions
#NB: We are no longer using `GOPATH`
#----------------------------------------------
* Language basics
#----------------------------------------------
* Creating packages
- Group related stuff
- Each package in dedicated directory
- More coarse-grained than Java: can contain multiple files
- Package name first line of source file
package main // package that results in executable with same name as package
or
package news // package that results in library that is accessible via 'news'
NB:
- Minimize exported surface
- Make it short and sweet: fmt, http, log, ..
#----------------------------------------------
* Using other packages <packageusage>
- Import
- Use package-name as prefix
.play -edit examples/packageusage/main.go
#----------------------------------------------
* Comments
/* a comment */ and // another one
Document your packages:
- Package level comment
- Every exported (capitalized) name in a program should have a comment
Verify documentation: should be a good summary
go doc -all
Enforce rules:
golint
- helps you minimize your public exports
#----------------------------------------------
* Commenting example <patientstore>
.play -edit examples/patientstore/patientstore.go
#----------------------------------------------
* Variables (vars)
- Name and type swapped (from Java perspective)
- Have reasonable defaults (not nil)
.play -edit examples/vars/vars.go /START OMIT/,/END OMIT/
#----------------------------------------------
* Loops <for,while,iterate>
- for
.play -edit examples/for/for.go /START OMIT/,/END OMIT/
- while-like
.play -edit examples/while/while.go /START OMIT/,/END OMIT/
- iterate
.play -edit examples/iterate/iterate.go /START OMIT/,/END OMIT/
#----------------------------------------------
* If, else <if>
.play -edit examples/if/if.go
#----------------------------------------------
* Switch <switching>
- On any type
- No fallthrough unless explicitly stated
- Multiple cases as comma-separated list
.code -edit examples/switching/switch.go /START OMIT/,/END OMIT/
#----------------------------------------------
* Exercise 2: Play around with control flow
Use dedicated directory for this exercise:
$ exercises/flow
Tasks:
- Sum of all values from 1 up to 100
- Sum incremental values untill their sum exceeds 1000, return number of loops
Peek: solutions/flow
#----------------------------------------------
* Functions
- Core building block
- Scope: based on case
- Java: static methods
func ConvertIt( arg int ) string { // public
return convertInternal( arg )
}
func convertInternal( arg int ) string { // internal, private function
return fmt.Sprintf( "My integer value as string: %d", arg)
}
- Can return multiple values
func swap(x, y string) (string, string) {
return y, x
}
(More on functions later)
#----------------------------------------------
* Exercise 3: Move function to dedicated library
Continue with previous exercise:
$ exercises/flow
Tasks:
- Put calculation logic in separate library
Peek: solutions/flow
#----------------------------------------------
* Error handling
- Multiple return values
- if error is nil, the call worked
resp, err := doSomethingThatCanFail(arg1, arg2)
if err != nil {
return fmt.Errorf("Error doing something that can fail: %s", err) // early return to minimize indentation
}
// continue with success path
// use _ (=blank) if you don't care
resp, _ := doit(arg1, arg2)
- Function signature tells that things can go wrong
- Keep indentation low
!!! All your own API's should use this pattern !!!
Do not use panic and recover
#----------------------------------------------
* Exercise 4: Idiomatic error-handling
Use dedicated directory for this exercise:
$ exercises/errorhandling
Tasks:
- Read a file
- Capitalize the content of the file
- Write this capitalized content to a different new file
- Use Proper error-handling
- Advanced: Read as json and write as xml
TIP:
- File access using the "io/ioutil"-package ("os" nowadays)
- Capitalize using "strings" or "bytes"-package
Peek: solutions/errorhandling
#----------------------------------------------
* Data
#----------------------------------------------
* Struct <struct>
- Equivalent to Java class
- Case of variable determines accessibility (private, public)
.play -edit examples/struct/struct.go /START OMIT/,/END OMIT/
#----------------------------------------------
* Initializing structs
student := Student{
FullName: "Freek Grol",
AddressLine: "...., De Bilt, Nederland",
Study: Study{
Name: "Geography",
},
ProgressYear: 3,
}
or
student := Student{} // Default values for all fields
or
student := Student{}
student.FullName = "Freek Grol"
student.AddressLine = "..."
#----------------------------------------------
* Pointers
- Pointer to memory where object resides
var intPointer *int = new(int)
*intPointer = 9
var patient *Patient = &Patient{}
patient2 := &Patient{}
var patient *Patient // nil (default value)
As parameters
func adjust( a *int ) {
*a = 9
}
func dosomethingWithSideEffects( p *Patient ) {
p.Age = 42
}
p := Patient{}
dosomethingWithSideEffects(&p)
#----------------------------------------------
* Why pointers?
- For methods that mutate data
func MarkDeceasedWrong(p Patient) { // patient NOT adjusted after function returns
p.Deceased = true
}
func MarkDeceased(p *Patient) { // patient adjusted after ..
p.Deceased = true
}
- For passing around huge structs
func ProcessRontgenImage ( img *Image ) { ... }
- Indicate Optional (poor mans)
type Person struct {
Name string
Car *Car // optional
}
#----------------------------------------------
* Initializing pointers
student := &Student{ // NOTE: starts with '&'
FullName: "... ",
AddressLine: "...., De Bilt, Nederland",
}
or
func NewStudent(fullName, adddressLine string,
birthdate time.Time,
studyName string, progressYear int) *Student { // NOTE: returns *
return &Student{
FullName: fullName,
AddressLine: adddressLine,
}
}
or
student := new(Student)
student.FullName = "Freek Grol"
student.AddressLine = "..."
#----------------------------------------------
* Struct methods <methods>
.play -edit examples/methods/methods.go /START OMIT/,/END OMIT/
#----------------------------------------------
* Enumerations <enum>
.play -edit examples/enum/enum.go /START OMIT/,/END OMIT/
#----------------------------------------------
#----------------------------------------------
* Slices (more on it later)
- Built-in (Generics!)
- Equivalent of an array/list
.play -edit solutions/model/model.go /START OMIT/,/END OMIT/
#----------------------------------------------
* Exercise 5: Model your business domain
Use dedicated directory for this exercise:
$ exercises/model
.image examples/images/uml.png
Tasks:
- Use structs, enums, pointers
- Use slices
Peek: solutions/model
#----------------------------------------------
* Containers
- array and slice
- map
#----------------------------------------------
* Slices
- Can contain everything: primitives, structs, slices, maps etc
- Like Java ArrayList
- Sortable
- Supported operations:
append, replace, get-on-idx, get-on-range, iterate
Fixed length (not extendable in size)
numbers := []int{10, 20, 30, 40}
s := [...]string{"Voetbal", "Hockey"} // idiomatic: let compiler count
Dynamic size (start small, auto extend)
var slice0 []string = []string{} // empty
slice1 := []string{} // empty
slice2 := []string{"a", "b", "c"} // initialize with data
slice3 := make( []string, 0, 5 ) // optimization: empty with reserved capacity
#----------------------------------------------
* Slices in action <slice>
.play -edit examples/slice/slice.go /START OMIT/,/END OMIT/
#----------------------------------------------
* Always keep result of append
// wrong
append( letters, "e" )
// right
letters = append(letters, "e")
Why?
- Realloc when no longer fits
- Returns new pointer
#----------------------------------------------
* Anonymous slice
- For one-time use only
.play -edit examples/anonymous/main.go /START OMIT/,/END OMIT/
- Useful for table driven tests
#----------------------------------------------
* Map
- Store key-value pairs (like Java HashMap)
- Typically key is primitive, value can be everything: primitives, structs, slices, maps etc
- Supported operations:
get-on-key, put-on-key, replace-on-key, delete-on-key, iterate
initialization:
var m1 map[string]int = make(map[string]int)
m2 := make(map[string]int)
m3 := map[string]int{}
m4 := map[string]int{
"route": 66,
}
- Random iteration order
#----------------------------------------------
* Maps in action <maps>
.play -edit examples/maps/maps.go /START OMIT/,/END OMIT/
#----------------------------------------------
* Exercise: slices and maps
Use dedicated directory for this exercise:
$ exercises/slicesmaps
Task:
- Use maps and slices to group the following people on hobby:
"Julia": "voetbal", "tekenen"
"Sophie": "hockey"
"Mila": "tekenen"
"Emma": "volleybal", "turnen"
"Tess": "hardlopen"
"Zoë": "kunst", "Voetbal"
"Noor": "voetbal"
"Elin": "Hockey"
"Sara": "voetbal", "turnen"
"Yara": "tekenen"
TIP: Copy and paste and use editor in column-mode
Peek: solutions/groupby
#----------------------------------------------
* Embedding
#----------------------------------------------
* Embedding
- Inheritance or composition?
.play -edit examples/sync/sync.go /START OMIT/,/END OMIT/
#----------------------------------------------
* Interfaces
#----------------------------------------------
* Interfaces
- Duck-typing: no explicit "implements"
- Very useful to improve testability (dependency injection)
example from stdlib
package fmt;
// Accepts anything that implements the "Writer"-interface:
// Examples of Writers: file, buffer, stdout, network, http-response, zip-file etc
func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) { ... }
io.Writer-interface:
type Writer interface {
Write(p []byte) (n int, err error)
}
#other example
# // The business logic layer can return this EnrichedError as regular 'error' .
# // The http layer convert this error into an appropriate http-response (200, 400, 403, 500 etc)
# type EnrichedError struct {
# Kind ErrorKind // invalid-input, not-authorized, internal-error etc
# Message string
# }
# func (e HttpError)Error() string { // implement Error-interface
# return e.Message
# }
# func GetHttpStatus(err error) int { ... }
# Refactor using interfaces when initially done
#----------------------------------------------
* Interface <interfaces>
- Naming convention: ends with "er". Doesn't happen too much in practise 😅
- Keep them small. Why?
- Composable
Typestrong variant
type Datastorer interface {
Put(patientUid string, patient Patient) error
Get(patientUid string) (Patient, bool, error)
Remove(patientUid string) error
}
Composable variant
package db
type Service interface {
UserService
DeviceService
}
#----------------------------------------------
* Example usage of interface <interfaces>
- For dependency injection
- The business logic of PatientService is testable without a "real"-datastore
.code -edit examples/interfaces/main.go /START OMIT/,/END OMIT/
#----------------------------------------------
* Any type
any (since 1.18)
Empty interface in the past:
interface{}
- Accepts anything
- NOT typestrong
- Like Java Object or void* in C
.play -edit examples/emptyinterface/main.go /START OMIT/,/END OMIT/
- Used by standard json and xml packages to (un) serialize
#----------------------------------------------
* Constructor function
type DataStorer interface {
...
}
type PatientDatastore struct {}
func New() DataStorer {
return &PatientDatastore{}
}
TIP: Write the constructor function first and let your IDE do the rest!
Use a pointer if the struct is large, or you want to modify the state
Implementation without constructor function:
type Service interface {
...
}
var _ Service = (*MockDeviceService)(nil)
type MockDeviceService struct {}
#----------------------------------------------
* Exercise: interfaces
Use dedicated directory for this exercise:
$ exercises/interfaces
Tasks:
- Implement a simple in-memory database that implements the following interface:
type Datastorer interface {
Put(key string, value interface{}) error
Get(key string) (interface{}, bool, error)
Remove(key string) error
}
TIP: Use a map as in-memory datastore
Peek: examples/interfaces
#----------------------------------------------
* More on functions
#----------------------------------------------
* Package initialisation
- Executed only once at startup of package
func init() {
rand.Seed(time.Now().UnixNano())
}
- For "const"-like struct initialisations
var knownMembers []Member
func init() {
knownMembers = []Member{
{ ... },
{ ... },
{ ... },
}
}
- Can be multiple, however the order of execution is random. So only use once
#----------------------------------------------
* Defer <defer>
- Guaranteed to be called when function returns
- Can be multiple, last defer is executed first
- Cleanup of file-handles, mutexes, channels and connections
- Debugging: log "enter" and "leave" of function