forked from miekg/learninggo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
learninggo-2.txt
6216 lines (4176 loc) · 186 KB
/
learninggo-2.txt
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 Working Group R. Gieben
Internet-Draft August 25, 2018
Intended status: Informational
Expires: February 26, 2019
Learning Go
draft-learning-go-00
Preface
The source of this book [1] is written in mmark [2] and is converted
from the original LaTeX source [3].
_All example code used in this book is hereby licensed under the
Apache License version 2.0._
This work is licensed under the Attribution-NonCommercial-
ShareAlike 3.0 Unported License. To view a copy of this license,
visit http://creativecommons.org/licenses/by-nc-sa/3.0/ [4] or
send a letter to Creative Commons, 171 Second Street, Suite 300,
San Francisco, California, 94105, USA.
The following people made large or small contributions to earlier
versions of this book:
Adam J. Gray, Alexander Katasonov, Alexey Chernenkov, Alex Sychev,
Andrea Spadaccini, Andrey Mirtchovski, Anthony Magro, Babu Sreekanth,
Ben Bullock, Bob Cunningham, Brian Fallik, Cecil New, Cobold, Damian
Gryski, Daniele Pala, Dan Kortschak, David Otton, Fabian Becker,
Filip Zaludek, Hadi Amiri, Haiping Fan, Iaroslav Tymchenko, Jaap
Akkerhuis, JC van Winkel, Jeroen Bulten, Jinpu Hu, John Shahid,
Jonathan Kans, Joshua Stein, Makoto Inoue, Marco Ynema, Mayuresh
Kathe, Mem, Michael Stapelberg, Nicolas Kaiser, Olexandr Shalakhin,
Paulo Pinto, Peter Kleiweg, Philipp Schmidt, Robert Johnson, Russel
Winder, Simoc, Sonia Keys, Stefan Schroeder, Thomas Kapplet, T.J.
Yang, Uriel"\dagger", Vrai Stacey, Xing Xing.
"Learning Go" has been translated into (note that this used the
original LaTeX source).
o Chinese, by Xing Xing, 这里是中文译本: http://www.mikespook.com/learning-
go/ [5]
I hope this book is useful.
Miek Gieben, London, 2015.
Gieben Expires February 26, 2019 [Page 1]
Internet-Draft Learning Go August 2018
This book still sees development, small incremental improvements
trickle in from Github.
Miek Gieben, London, 2017.
Learning Go's source has been rewritten in mmark2 [6], but did not
see any other changes. This books translates cleanly into an RFC-
like document [7].
Miek Gieben, London, 2018.
Status of This Memo
This Internet-Draft is submitted in full conformance with the
provisions of BCP 78 and BCP 79.
Internet-Drafts are working documents of the Internet Engineering
Task Force (IETF). Note that other groups may also distribute
working documents as Internet-Drafts. The list of current Internet-
Drafts is at https://datatracker.ietf.org/drafts/current/.
Internet-Drafts are draft documents valid for a maximum of six months
and may be updated, replaced, or obsoleted by other documents at any
time. It is inappropriate to use Internet-Drafts as reference
material or to cite them other than as "work in progress."
This Internet-Draft will expire on February 26, 2019.
Copyright Notice
Copyright (c) 2018 IETF Trust and the persons identified as the
document authors. All rights reserved.
This document is subject to BCP 78 and the IETF Trust's Legal
Provisions Relating to IETF Documents
(https://trustee.ietf.org/license-info) in effect on the date of
publication of this document. Please review these documents
carefully, as they describe your rights and restrictions with respect
to this document. Code Components extracted from this document must
include Simplified BSD License text as described in Section 4.e of
the Trust Legal Provisions and are provided without warranty as
described in the Simplified BSD License.
Gieben Expires February 26, 2019 [Page 2]
Internet-Draft Learning Go August 2018
Table of Contents
1. Learning Go . . . . . . . . . . . . . . . . . . . . . . . . . 6
2. Introduction . . . . . . . . . . . . . . . . . . . . . . . . 6
2.1. How to Read this Book . . . . . . . . . . . . . . . . . . 7
2.2. Official Documentation . . . . . . . . . . . . . . . . . 8
3. Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3.1. Hello World . . . . . . . . . . . . . . . . . . . . . . . 9
3.2. Compiling and Running Code . . . . . . . . . . . . . . . 10
3.3. Variables, Types and Keywords . . . . . . . . . . . . . . 10
3.3.1. Boolean Types . . . . . . . . . . . . . . . . . . . . 11
3.3.2. Numerical Types . . . . . . . . . . . . . . . . . . . 11
3.3.3. Constants . . . . . . . . . . . . . . . . . . . . . . 12
3.3.4. Strings . . . . . . . . . . . . . . . . . . . . . . . 12
3.3.5. Runes . . . . . . . . . . . . . . . . . . . . . . . . 13
3.3.6. Complex Numbers . . . . . . . . . . . . . . . . . . . 13
3.3.7. Errors . . . . . . . . . . . . . . . . . . . . . . . 13
3.4. Operators and Built-in Functions . . . . . . . . . . . . 13
3.5. Go Keywords . . . . . . . . . . . . . . . . . . . . . . . 14
3.6. Control Structures . . . . . . . . . . . . . . . . . . . 15
3.6.1. If-Else . . . . . . . . . . . . . . . . . . . . . . . 15
3.6.2. Goto . . . . . . . . . . . . . . . . . . . . . . . . 16
3.6.3. For . . . . . . . . . . . . . . . . . . . . . . . . . 16
3.6.4. Break and Continue . . . . . . . . . . . . . . . . . 16
3.6.5. Range . . . . . . . . . . . . . . . . . . . . . . . . 17
3.6.6. Switch . . . . . . . . . . . . . . . . . . . . . . . 18
3.7. Built-in Functions . . . . . . . . . . . . . . . . . . . 19
3.8. Arrays, Slices, and Maps . . . . . . . . . . . . . . . . 20
3.8.1. Arrays . . . . . . . . . . . . . . . . . . . . . . . 20
3.8.2. Slices . . . . . . . . . . . . . . . . . . . . . . . 21
3.8.3. Maps . . . . . . . . . . . . . . . . . . . . . . . . 23
3.9. Exercises . . . . . . . . . . . . . . . . . . . . . . . . 25
3.9.1. For-loop . . . . . . . . . . . . . . . . . . . . . . 25
3.9.2. Answer . . . . . . . . . . . . . . . . . . . . . . . 25
3.9.3. Average . . . . . . . . . . . . . . . . . . . . . . . 26
3.9.4. Answer . . . . . . . . . . . . . . . . . . . . . . . 26
3.9.5. FizzBuzz . . . . . . . . . . . . . . . . . . . . . . 27
3.9.6. Answer . . . . . . . . . . . . . . . . . . . . . . . 27
4. Functions . . . . . . . . . . . . . . . . . . . . . . . . . . 28
4.1. Scope . . . . . . . . . . . . . . . . . . . . . . . . . . 30
4.2. Functions as values . . . . . . . . . . . . . . . . . . . 31
4.3. Callbacks . . . . . . . . . . . . . . . . . . . . . . . . 31
4.4. Deferred Code . . . . . . . . . . . . . . . . . . . . . . 32
4.5. Variadic Parameter . . . . . . . . . . . . . . . . . . . 34
4.6. Panic and recovering . . . . . . . . . . . . . . . . . . 34
4.7. Exercises . . . . . . . . . . . . . . . . . . . . . . . . 36
4.7.1. Average . . . . . . . . . . . . . . . . . . . . . . . 36
4.7.2. Answer . . . . . . . . . . . . . . . . . . . . . . . 36
Gieben Expires February 26, 2019 [Page 3]
Internet-Draft Learning Go August 2018
4.7.3. Bubble sort . . . . . . . . . . . . . . . . . . . . . 37
4.7.4. Answer . . . . . . . . . . . . . . . . . . . . . . . 37
4.7.5. For-loop II . . . . . . . . . . . . . . . . . . . . . 38
4.7.6. Answer . . . . . . . . . . . . . . . . . . . . . . . 38
4.7.7. Fibonacci . . . . . . . . . . . . . . . . . . . . . . 38
4.7.8. Answer . . . . . . . . . . . . . . . . . . . . . . . 38
4.7.9. Var args . . . . . . . . . . . . . . . . . . . . . . 39
4.7.10. Answer . . . . . . . . . . . . . . . . . . . . . . . 39
4.7.11. Functions that return functions . . . . . . . . . . . 39
4.7.12. Answer . . . . . . . . . . . . . . . . . . . . . . . 39
4.7.13. Maximum . . . . . . . . . . . . . . . . . . . . . . . 40
4.7.14. Answer . . . . . . . . . . . . . . . . . . . . . . . 40
4.7.15. Map function . . . . . . . . . . . . . . . . . . . . 40
4.7.16. Answer . . . . . . . . . . . . . . . . . . . . . . . 41
4.7.17. Stack . . . . . . . . . . . . . . . . . . . . . . . . 41
4.7.18. Answer . . . . . . . . . . . . . . . . . . . . . . . 41
5. Packages . . . . . . . . . . . . . . . . . . . . . . . . . . 43
5.1. Identifiers . . . . . . . . . . . . . . . . . . . . . . . 45
5.2. Documenting packages . . . . . . . . . . . . . . . . . . 46
5.3. Testing packages . . . . . . . . . . . . . . . . . . . . 47
5.4. Useful packages . . . . . . . . . . . . . . . . . . . . . 49
5.5. Exercises . . . . . . . . . . . . . . . . . . . . . . . . 51
5.5.1. Stack as package . . . . . . . . . . . . . . . . . . 51
5.5.2. Answer . . . . . . . . . . . . . . . . . . . . . . . 51
5.5.3. Calculator . . . . . . . . . . . . . . . . . . . . . 52
5.5.4. Answer . . . . . . . . . . . . . . . . . . . . . . . 52
6. Beyond the basics . . . . . . . . . . . . . . . . . . . . . . 54
6.1. Allocation . . . . . . . . . . . . . . . . . . . . . . . 55
6.1.1. Allocation with new . . . . . . . . . . . . . . . . . 55
6.1.2. Allocation with make . . . . . . . . . . . . . . . . 55
6.1.3. Constructors and composite literals . . . . . . . . . 56
6.2. Defining your own types . . . . . . . . . . . . . . . . . 57
6.2.1. More on structure fields . . . . . . . . . . . . . . 58
6.2.2. Methods . . . . . . . . . . . . . . . . . . . . . . . 59
6.3. Conversions . . . . . . . . . . . . . . . . . . . . . . . 60
6.3.1. User defined types and conversions . . . . . . . . . 61
6.4. Exercises . . . . . . . . . . . . . . . . . . . . . . . . 62
6.4.1. Map function with interfaces . . . . . . . . . . . . 62
6.4.2. Answer . . . . . . . . . . . . . . . . . . . . . . . 62
6.4.3. Pointers . . . . . . . . . . . . . . . . . . . . . . 63
6.4.4. Answer . . . . . . . . . . . . . . . . . . . . . . . 63
6.4.5. Linked List . . . . . . . . . . . . . . . . . . . . . 63
6.4.6. Answer . . . . . . . . . . . . . . . . . . . . . . . 64
6.4.7. Cat . . . . . . . . . . . . . . . . . . . . . . . . . 66
6.4.8. Answer . . . . . . . . . . . . . . . . . . . . . . . 66
6.4.9. Method calls . . . . . . . . . . . . . . . . . . . . 70
6.4.10. Answer . . . . . . . . . . . . . . . . . . . . . . . 70
7. Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . 71
Gieben Expires February 26, 2019 [Page 4]
Internet-Draft Learning Go August 2018
7.1. Which is what? . . . . . . . . . . . . . . . . . . . . . 72
7.2. Empty interface . . . . . . . . . . . . . . . . . . . . . 73
7.3. Methods . . . . . . . . . . . . . . . . . . . . . . . . . 74
7.4. Methods on interface types . . . . . . . . . . . . . . . 74
7.5. Interface names . . . . . . . . . . . . . . . . . . . . . 75
7.6. A sorting example . . . . . . . . . . . . . . . . . . . . 75
7.7. Listing interfaces in interfaces . . . . . . . . . . . . 77
7.8. Introspection and reflection . . . . . . . . . . . . . . 78
7.9. Exercises . . . . . . . . . . . . . . . . . . . . . . . . 80
7.9.1. Answer . . . . . . . . . . . . . . . . . . . . . . . 80
7.9.2. Pointers and reflection . . . . . . . . . . . . . . . 81
7.9.3. Answer . . . . . . . . . . . . . . . . . . . . . . . 82
8. Concurrency . . . . . . . . . . . . . . . . . . . . . . . . . 82
8.1. Make it run in parallel . . . . . . . . . . . . . . . . . 85
8.2. More on channels . . . . . . . . . . . . . . . . . . . . 85
8.3. Exercises . . . . . . . . . . . . . . . . . . . . . . . . 86
8.3.1. Channels . . . . . . . . . . . . . . . . . . . . . . 86
8.3.2. Answer . . . . . . . . . . . . . . . . . . . . . . . 86
8.3.3. Fibonacci II . . . . . . . . . . . . . . . . . . . . 88
8.3.4. Answer . . . . . . . . . . . . . . . . . . . . . . . 89
9. Communication . . . . . . . . . . . . . . . . . . . . . . . . 90
9.1. io.Reader . . . . . . . . . . . . . . . . . . . . . . . . 91
9.2. Some examples . . . . . . . . . . . . . . . . . . . . . . 92
9.3. Command line arguments . . . . . . . . . . . . . . . . . 92
9.4. Executing commands . . . . . . . . . . . . . . . . . . . 93
9.5. Networking . . . . . . . . . . . . . . . . . . . . . . . 93
9.6. Exercises . . . . . . . . . . . . . . . . . . . . . . . . 94
9.6.1. Finger daemon . . . . . . . . . . . . . . . . . . . . 94
9.6.2. Answer . . . . . . . . . . . . . . . . . . . . . . . 95
9.6.3. Echo server . . . . . . . . . . . . . . . . . . . . . 96
9.6.4. Answer . . . . . . . . . . . . . . . . . . . . . . . 96
9.6.5. Word and Letter Count . . . . . . . . . . . . . . . . 98
9.6.6. Answer . . . . . . . . . . . . . . . . . . . . . . . 98
9.6.7. Uniq . . . . . . . . . . . . . . . . . . . . . . . . 99
9.6.8. Answer . . . . . . . . . . . . . . . . . . . . . . . 99
9.6.9. Quine . . . . . . . . . . . . . . . . . . . . . . . . 99
9.6.10. Answer . . . . . . . . . . . . . . . . . . . . . . . 100
9.6.11. Processes . . . . . . . . . . . . . . . . . . . . . . 100
9.6.12. Answer . . . . . . . . . . . . . . . . . . . . . . . 101
9.6.13. Number cruncher . . . . . . . . . . . . . . . . . . . 102
9.6.14. Answer . . . . . . . . . . . . . . . . . . . . . . . 103
10. References . . . . . . . . . . . . . . . . . . . . . . . . . 106
10.1. Informative References . . . . . . . . . . . . . . . . . 106
10.2. URIs . . . . . . . . . . . . . . . . . . . . . . . . . . 107
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
Author's Address . . . . . . . . . . . . . . . . . . . . . . . . 111
Gieben Expires February 26, 2019 [Page 5]
Internet-Draft Learning Go August 2018
1. Learning Go
fig/bumper-inverse.png
2. Introduction
Is Go an object-oriented language? Yes and no.
------------------------------------------------------------
Frequently asked questions, Go Authors
The Go programming language is an open source project language to
make programmers more productive.
According to the website [go_web] "Go is expressive, concise, clean,
and efficient". And indeed it is. My initial interest was piqued
when I read early announcements about this new language that had
built-in concurreny and a C-like syntax (Erlang also has built-in
concurrency, but I could never get used to its syntax). Go is a
compiled statically typed language that feels like a dynamically
typed, interpreted language. My go to (scripting!) language Perl has
taken a back seat now that Go is around.
The unique Go language is defined by these principles:
Clean and Simple
Go strives to keep things small and beautiful. You should be able
to do a lot in only a few lines of code.
Concurrent
Go makes it easy to "fire off" functions to be run as _very_
lightweight threads. These threads are called goroutines in Go.
Channels
Communication with these goroutines is done, either via shared
state or via channels [csp].
Fast
Compilation is fast and execution is fast. The aim is to be as
fast as C. Compilation time is measured in seconds.
Safe
Explicit casting and strict rules when converting one type to
another. Go has garbage collection. No more "free()" in Go: the
language takes care of this.
Standard format
Gieben Expires February 26, 2019 [Page 6]
Internet-Draft Learning Go August 2018
A Go program can be formatted in (almost) any way the programmers
want, but an official format exists. The rule is very simple: The
output of the filter "gofmt" _is the officially endorsed format_.
Postfix types
Types are given _after_ the variable name, thus "var a int",
instead of "int a".
UTF-8
UTF-8 is everywhere, in strings _and_ in the program code.
Finally you can use "\Phi = \Phi + 1" in your source code.
Open Source
The Go license is completely open source.
Fun
Programming with Go should be fun!
As I mentioned Erlang also shares some features of Go. A notable
difference between Erlang and Go is that Erlang borders on being a
functional language, while Go is imperative. And Erlang runs in a
virtual machine, while Go is compiled.
2.1. How to Read this Book
I've written this book for people who already know some programming
languages and how to program. In order to use this book, you (of
course) need Go installed on your system, but you can easily try
examples online in the Go playground. All exercises in this book
work with Go 1, the first stable release of Go -- if not, it's a bug.
The best way to learn Go is to create your own programs. Each
chapter therefore includes exercises (and answers to exercises) to
acquaint you with the language. Each exercise is either _easy_,
_intermediate_, or _difficult_. The answers are included after the
exercises on a new page. Some exercises don't have an answer; these
are marked with an asterisk.
Here's what you can expect from each chapter:
basics
We'll look at the basic types, variables, and control structures
available in the language.
functions
Here we look at functions, the basic building blocks of Go
programs.
Gieben Expires February 26, 2019 [Page 7]
Internet-Draft Learning Go August 2018
packages
We'll see that functions and data can be grouped together in
packages. We'll also see how to document and test our packages.
beyond-the-basics
We'll create our own types. We'll also look at memory allocations
in Go.
interfaces
We'll learn how to use interfaces. Interfaces are the central
concept in Go, as Go does not support object orientation in the
traditional sense.
concurrency
We'll learn the "go" keyword, which can be used to start function
in separate routines (called goroutines). Communication with
those goroutines is done via channels.
communication
Finally we'll see how to interface with the rest of the world from
within a Go program. We'll see how to create files and read and
write to and from them. We'll also briefly look into networking.
2.2. Official Documentation
There is a substantial amount of documentation written about Go. The
Go Tutorial [go_tutorial], the Go Tour (with lots of exercises) and
the Effective Go [effective_go] are helpful resources. The website
http://golang.org/doc/ [8] is a very good starting point for reading
up on Go. Reading these documents is certainly not required, but it
is recommended.
When searching on the internet use the term "golang" instead of
plain "go".
Go comes with its own documentation in the form of a program called
"godoc". If you are interested in the documentation for the built-
ins, simply do this:
% godoc builtin
To get the documentation of the "hash" package, just:
% godoc hash
To read the documentation of "fnv" contained in "hash", you'll need
to issue "godoc hash/fnv" as "fnv" is a subdirectory of "hash".
Gieben Expires February 26, 2019 [Page 8]
Internet-Draft Learning Go August 2018
PACKAGE DOCUMENTATION
package fnv
import "hash/fnv"
Package fnv implements FNV-1 and FNV-1a, non-cryptographic hash
...
3. Basics
I am interested in this and hope to do something.
------------------------------------------------------------
On adding complex numbers to Go, Ken Thompson
In this chapter we will look at the basic building blocks of the Go
programming language.
3.1. Hello World
In the Go tutorial, you get started with Go in the typical manner:
printing "Hello World" (Ken Thompson and Dennis Ritchie started this
when they presented the C language in the 1970s). That's a great way
to start, so here it is, "Hello World" in Go.
package main <1>
import "fmt" <2> // Implements formatted I/O.
/* Print something */ <3>
func main() { <4>
fmt.Printf("Hello, world.") <5>
}
Lets look at the program line by line. This first line is just
required _1_. All Go files start with "package <something>", and
"package main" is required for a standalone executable.
"import "fmt"" says we need "fmt" in addition to "main" _2_. A
package other than "main" is commonly called a library, a familiar
concept in many programming languages (see Section 5). The line ends
with a comment that begins with "//".
Next we another comment, but this one is enclosed in "/*" "*/" _3_.
When your Go program is executed, the first function called will be
"main.main()", which mimics the behavior from C. Here we declare
that function _4_.
Gieben Expires February 26, 2019 [Page 9]
Internet-Draft Learning Go August 2018
Finally we call a function from the package "fmt" to print a string
to the screen. The string is enclosed with """ and may contain non-
ASCII characters _5_.
3.2. Compiling and Running Code
To build a Go program, use the "go" tool. To build "helloworld" we
just enter:
% go build helloworld.go
This results in an executable called "helloworld".
% ./helloworld
Hello, world.
You can combine the above and just call "go run helloworld.go".
3.3. Variables, Types and Keywords
In the next few sections we will look at the variables, basic types,
keywords, and control structures of our new language.
Go is different from (most) other languages in that the type of a
variable is specified _after_ the variable name. So not: "int a",
but "a int". When you declare a variable it is assigned the
"natural" null value for the type. This means that after "var a
int", "a" has a value of 0. With "var s string", "s" is assigned the
zero string, which is """". Declaring and assigning in Go is a two
step process, but they may be combined. Compare the following pieces
of code which have the same effect.
var a int a := 15
var b bool b := false
a = 15
b = false
On the left we use the "var" keyword to declare a variable and _then_
assign a value to it. The code on the right uses ":=" to do this in
one step (this form may only be used _inside_ functions). In that
case the variable type is _deduced_ from the value. A value of 15
indicates an "int". A value of "false" tells Go that the type should
be "bool". Multiple "var" declarations may also be grouped; "const"
(see Section 3.3.3) and "import" also allow this. Note the use of
parentheses instead of braces:
Gieben Expires February 26, 2019 [Page 10]
Internet-Draft Learning Go August 2018
var (
x int
b bool
)
Multiple variables of the same type can also be declared on a single
line: "var x, y int" makes "x" and "y" both "int" variables. You can
also make use of _parallel assignment_ "a, b := 20, 16". This makes
"a" and "b" both integer variables and assigns 20 to "a" and 16 to
"b".
A special name for a variable is "_". Any value assigned to it is
discarded (it's similar to "/dev/null" on Unix). In this example we
only assign the integer value of 35 to "b" and discard the value 34:
"_, b := 34, 35". Declared but otherwise _unused_ variables are a
compiler error in Go.
3.3.1. Boolean Types
A boolean type represents the set of boolean truth values denoted by
the predeclared constants _true_ and _false_. The boolean type is
"bool".
3.3.2. Numerical Types
Go has most of the well-known types such as "int". The "int" type
has the appropriate length for your machine, meaning that on a 32-bit
machine it is 32 bits and on a 64-bit machine it is 64 bits. Note:
an "int" is either 32 or 64 bits, no other values are defined. Same
goes for "uint", the unsigned int.
If you want to be explicit about the length, you can have that too,
with "int32", or "uint32". The full list for (signed and unsigned)
integers is "int8", "int16", "int32", "int64" and "byte", "uint8",
"uint16", "uint32", "uint64", with "byte" being an alias for "uint8".
For floating point values there is "float32" and "float64" (there is
no "float" type). A 64 bit integer or floating point value is
_always_ 64 bit, also on 32 bit architectures.
Note that these types are all distinct and assigning variables which
mix these types is a compiler error, like in the following code:
Gieben Expires February 26, 2019 [Page 11]
Internet-Draft Learning Go August 2018
package main
func main() {
var a int
var b int32
b = a + a
b = b + 5
}
We declare two different integers, a and b where a is an "int" and b
is an "int32". We want to set b to the sum of a and a. This fails
and gives the error: "cannot use a + a (type int) as type int32 in
assignment". Adding the constant 5 to b _does_ succeed, because
constants are not typed.
3.3.3. Constants
Constants in Go are just that --- constant. They are created at
compile time, and can only be numbers, strings, or booleans; "const x
= 42" makes "x" a constant. You can use _iota_ to enumerate values.
const (
a = iota
b
)
The first use of "iota" will yield 0, so "a" is equal to 0. Whenever
"iota" is used again on a new line its value is incremented with 1,
so "b" has a value of 1. Or, as shown here, you can even let Go
repeat the use of "iota". You may also explicitly type a constant:
"const b string = "0"". Now "b" is a "string" type constant.
3.3.4. Strings
Another important built-in type is "string". Assigning a string is
as simple as:
s := "Hello World!"
Strings in Go are a sequence of UTF-8 characters enclosed in double
quotes ("). If you use the single quote (') you mean one character
(encoded in UTF-8) --- which is _not_ a "string" in Go.
Once assigned to a variable, the string cannot be changed: strings in
Go are immutable. If you are coming from C, note that the following
is not legal in Go:
Gieben Expires February 26, 2019 [Page 12]
Internet-Draft Learning Go August 2018
var s string = "hello"
s[0] = 'c'
To do this in Go you will need the following:
s := "hello"
c := []rune(s) <1>
c[0] = 'c' <2>
s2 := string(c) <3>
fmt.Printf("%s\n", s2) <4>
Here we convert "s" to an array of runes _1_. We change the first
element of this array _2_. Then we create a _new_ string "s2" with
the alteration _3_. Finally, we print the string with "fmt.Printf"
_4_.
3.3.5. Runes
"Rune" is an alias for "int32". It is an UTF-8 encoded code point.
When is this type useful? One example is when you're iterating over
characters in a string. You could loop over each byte (which is only
equivalent to a character when strings are encoded in 8-bit ASCII,
which they are _not_ in Go!). But to get the actual characters you
should use the "rune" type.
3.3.6. Complex Numbers
Go has native support for complex numbers. To use them you need a
variable of type "complex128" (64 bit real and imaginary parts) or
"complex64" (32 bit real and imaginary parts). Complex numbers are
written as "re + im""i", where "re" is the real part, "im" is the
imaginary part and "i" is the literal '"i"' ("\sqrt{-1}").
3.3.7. Errors
Any non-trivial program will have the need for error reporting sooner
or later. Because of this Go has a builtin type specially for
errors, called "error". "var e error" creates a variable "e" of type
"error" with the value "nil". This error type is an interface --
we'll look more at interfaces in Section 7. For now you can just
assume that "error" is a type just like all other types.
3.4. Operators and Built-in Functions
Go supports the normal set of numerical operators. See Table 1 for
lists the current ones and their relative precedence. They all
associate from left to right.
Gieben Expires February 26, 2019 [Page 13]
Internet-Draft Learning Go August 2018
+------------+------------------------+
| Precedence | Operator(s) |
+------------+------------------------+
| Highest | * / % << >> & &^ |
| | `+ - |
| | == != < <= > >= |
| | <- |
| | && |
| Lowest | || |
+------------+------------------------+
Table 1: Operator precedence.
"+ - * /" and "%" all do what you would expect, "& | ^" and "&^" are
bit operators for bitwise _and_ bitwise _or_ bitwise _xor_ and bit
clear respectively. The "&&" and "||" operators are logical _and_
and logical _or_ Not listed in the table is the logical not "!"
Although Go does not support operator overloading (or method
overloading for that matter), some of the built-in operators _are_
overloaded. For instance, "+" can be used for integers, floats,
complex numbers and strings (adding strings is concatenating them).
3.5. Go Keywords
Let's start looking at keywords, Table 2 lists all the keywords in
Go.
+-----------+--------------+---------+-----------+--------+
| break | default | func | interface | select |
| case | defer | go | map | struct |
| chan | else | goto | package | switch |
| const | fallthrough | if | range | type |
| continue | for | import | return | var |
+-----------+--------------+---------+-----------+--------+
Table 2: Keywords in Go.
We've seen some of these already. We used "var" and "const" in the
Section 3.3 section, and we briefly looked at "package" and "import"
in our "Hello World" program at the start of the chapter. Others
need more attention and have their own chapter or section:
o "func" is used to declare functions and methods.
o "return" is used to return from functions. We'll look at both
"func" and "return" in detail in Section 4.
Gieben Expires February 26, 2019 [Page 14]
Internet-Draft Learning Go August 2018
o "go" is used for concurrency. We'll look at this in
Section 8.3.1.
o "select" used to choose from different types of communication,
We'll work with "select" in Section 8.3.1.
o "interface" is covered in Section 7.
o "struct" is used for abstract data types. We'll work with
"struct" in Section 6.
o "type" is also covered in Section 6.
3.6. Control Structures
There are only a few control structures in Go. To write loops we use
the "for" keyword, and there is a "switch" and of course an "if".
When working with channels "select" will be used (see Section 8.3.1).
Parentheses are not required around the condition, and the body must
_always_ be brace-delimited.
3.6.1. If-Else
In Go an "if" looks like this:
if x > 0 {
return y
} else {
return x
}
Since "if" and "switch" accept an initialization statement, it's
common to see one used to set up a (local) variable.
if err := SomeFunction(); err == nil {
// do something
} else {
return err
}
It is idomatic in Go to omit the "else" when the "if" statement's
body has a "break", "continue", "return" or, "goto", so the above
code would be better written as:
if err := SomeFunction(); err != nil {
return err
}
// do something
Gieben Expires February 26, 2019 [Page 15]
Internet-Draft Learning Go August 2018
The opening brace on the first line must be positioned on the same
line as the "if" statement. There is no arguing about this, because
this is what "gofmt" outputs.
3.6.2. Goto
Go has a "goto" statement - use it wisely. With "goto" you jump to a
label which must be defined within the current function. For
instance, a loop in disguise:
func myfunc() {
i := 0
Here:
fmt.Println(i)
i++
goto Here
}
The string "Here:" indicates a label. A label does not need to start
with a capital letter and is case sensitive.
3.6.3. For
The Go "for" loop has three forms, only one of which has semicolons:
o "for init; condition; post { }" - a loop using the syntax borrowed
from C;
o "for condition { }" - a while loop, and;
o "for { }" - an endless loop.
Short declarations make it easy to declare the index variable right
in the loop.
sum := 0
for i := 0; i < 10; i++ {
sum = sum + i
}
Note that the variable "i" ceases to exist after the loop.
3.6.4. Break and Continue
With "break" you can quit loops early. By itself, "break" breaks the
current loop.
Gieben Expires February 26, 2019 [Page 16]
Internet-Draft Learning Go August 2018
for i := 0; i < 10; i++ {
if i > 5 {
break <1>
}
fmt.Println(i) <2>
}
Here we "break" the current loop _1_, and don't continue with the
"fmt.Println(i)" statement _2_. So we only print 0 to 5. With loops
within loop you can specify a label after "break" to identify _which_
loop to stop:
J: for j := 0; j < 5; j++ { <1>
for i := 0; i < 10; i++ {
if i > 5 {
break J <2>
}
fmt.Println(i)
}
}
Here we define a label "J" _1_, preceding the "for"-loop there. When
we use "break J" _2_, we don't break the inner loop but the "J" loop.
With "continue" you begin the next iteration of the loop, skipping
any remaining code. In the same way as "break", "continue" also
accepts a label.
3.6.5. Range
The keyword "range" can be used for loops. It can loop over slices,
arrays, strings, maps and channels (see Section 8.3.1). "range" is an
iterator that, when called, returns the next key-value pair from the
"thing" it loops over. Depending on what that is, "range" returns
different things.
When looping over a slice or array, "range" returns the index in the
slice as the key and value belonging to that index. Consider this
code:
list := []string{"a", "b", "c", "d", "e", "f"}
for k, v := range list {
// do something with k and v
}
First we create a slice of strings. Then we use "range" to loop over
them. With each iteration, "range" will return the index as an "int"
Gieben Expires February 26, 2019 [Page 17]
Internet-Draft Learning Go August 2018
and the key as a "string". It will start with 0 and "a", so "k" will
be 0 through 5, and v will be "a" through "f".
You can also use "range" on strings directly. Then it will break out
the individual Unicode characters ^[In the UTF-8 world characters are
sometimes called _runes_ Mostly, when people talk about characters,
they mean 8 bit characters. As UTF-8 characters may be up to 32 bits
the word rune is used. In this case the type of "char" is "rune".
and their start position, by parsing the UTF-8. The loop:
for pos, char := range "Gő!" {
fmt.Printf("character '%c' starts at byte position %d\n", char, pos)
}
prints
character 'G' starts at byte position 0
character 'ő' starts at byte position 1
character '!' starts at byte position 3
Note that "ő" took 2 bytes, so '!' starts at byte 3.
3.6.6. Switch
Go's "switch" is very flexible; you can match on much more than just
integers. The cases are evaluated top to bottom until a match is
found, and if the "switch" has no expression it switches on "true".
It's therefore possible -- and idiomatic -- to write an "if-else-if-
else" chain as a "switch".
// Convert hexadecimal character to an int value
switch { <1>
case '0' <= c && c <= '9': <2>
return c - '0' <3>
case 'a' <= c && c <= 'f': <4>
return c - 'a' + 10
case 'A' <= c && c <= 'F': <5>
return c - 'A' + 10
}
return 0
A "switch" without a condition is the same as "switch true" _1_. We
list the different cases. Each "case" statement has a condition that
is either true of false. Here _2_ we check if "c" is a number. If