-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
01_fundamentals.slide
2461 lines (1266 loc) · 87.7 KB
/
01_fundamentals.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
Introduction to Go
1 - Fundamentals
Julien Cretel
https://jub0bs.com
https://bsky.app/profile/jub0bs.com
https://infosec.exchange/@jub0bs
* Hello, World!
You can play with the following program [[https://go.dev/play/p/7vin2BK8_A6][in the Go Playground]].
.play -edit src/helloworld.go
.image https://go.dev/blog/gopher/plush.jpg 200 _
* Some lessons from the Hello World program
Each source file starts with a [[https://go.dev/ref/spec#Package_clause][_package_clause_]], which states which package the source file belongs to:
package main
A package named `main` produces a _command_ or _executable_program_. In contrast, other packages correspond to _libraries_, which are packages importable by other packages.
[[https://go.dev/ref/spec#Import_declarations][_Import_declarations_]] specify _import_paths_ in double quotes:
: import paths require quotes like in Ruby: require 'json'
import "fmt"
The `main` function is a program's entrypoint; it has no parameters and no results:
func main()
Command-line arguments can be retrieved via [[https://pkg.go.dev/os#Args][a variable named `os.Args`]].
* Semicolons
Go's formal grammar [[https://go.dev/ref/spec#Semicolons][uses semicolons as statement terminators]] but, in contrast to C-like languages, semicolons do not appear in the source and are [[https://go.dev/doc/effective_go#semicolons][added by the compiler]].
As a result, line breaks can only occur in limited places. Consider this program:
package main
import "fmt"
func main()
{
fmt.Println("Hello, 世界")
}
Attempts to compile it fail with the following error message:
syntax error: unexpected semicolon or newline before {
The closing parenthesis and the opening brace must indeed appear on the same line.
* Formatting and file encoding
Go [[https://www.youtube.com/watch?v=sln-gJaURzk&t=28m55s][uses tabs (not spaces) for indentation]]. You'll never need to worry about indenting your code yourself, because Go provides a formatting tool: `gofmt`.
You can trigger `gofmt` by pressing the _Format_ button in the Go Playground:
.image img/go_playground_format.png 150 _
Moreover, if you've properly set up your IDE for Go, it will run `gofmt` upon file save.
`gofmt` is [[https://www.youtube.com/watch?v=sln-gJaURzk&t=30m58s][a huge time saver]], both for writing and reading code. Before contributing changes to a Go project, make sure you format your code with `gofmt`!
Finally, be aware that Go source files [[https://go.dev/ref/spec#Source_code_representation][*must* be encoded in UTF-8]], or compilation will fail.
: also: https://www.youtube.com/watch?v=yE5Tpp2BSGw&t=10m40s
* Modules
Go's solution to dependency management is known as the [[https://go.dev/doc/modules/managing-dependencies][_modules_system_]].
The terms _package_ and _module_ are confusingly similar, but don't conflate the two!
- A _package_ is a unit of code composed of one or more source files.
- A _module_ is a collection of packages versioned together using [[https://semver.org/][semantic versioning]] (and stored in a file tree with a `go.mod` file at its root).
.image img/modules_vs_packages.svg 250 _
: https://go.dev/blog/using-go-modules
: https://excalidraw.com/#json=buuEXMFgpGowzDhZMWzi7,5QOjQiY9GoMUNHGHCGL5_w
* The path of a module
A module is identified by its _path_, which takes the form of a domain followed by a path where you will release its source code. A module's path should be globally unique.
For instance, if you intend to publish your code on GitHub, the path of your module should have the following format:
github.com/YOUR_GITHUB_USERNAME/REPO_NAME
A module's path acts as the import path for the module's root directory. It prefixes the import paths of all the packages contained within the module:
import "github.com/YOUR_GITHUB_USERNAME/REPO_NAME/SOME_PACKAGE_NAME"
Note the absence of a central server (like [[https://npmjs.com]]) where modules ought to be published! As the Go team [[https://cacm.acm.org/magazines/2022/5/260357-the-go-programming-language-and-environment/fulltext#body-11][puts it]]: "Relying on domain names avoided a rush to claim valuable entries in a flat [namespace]."
* Initializing a module
When starting a project, you should initialize a module in the project's root folder.
: (Multi-module projects do exist but are rare and invite complication.)
To do so, `cd` to the root of your project and run a command of the following form:
$ go mod init <your-module-path>
Initializing a module creates a text file named `go.mod` in the current directory.
Don't forget to track this file in your version-control system, as it contains vital information about your project!
Resist the temptation to edit that file manually. Instead, you can interact with it solely through the use of the `mod` subcommand. For help, run
$ go help mod
* Namecheck project: initialize a module
1. Create a root folder named `namecheck` for your project and `cd` into it.
2. At the root of your project, initialize a module by running a command of this form:
$ go mod init github.com/YOUR_GITHUB_USERNAME/namecheck
A `go.mod` file will be created at the root of your project:
namecheck
└── go.mod
3. Inspect the contents of the `go.mod` file. It should look something like this:
module github.com/jub0bs/namecheck
go 1.23.2
- The [[https://go.dev/ref/mod#go-mod-file-module][`module` directive]] defines the module's path.
- The [[https://go.dev/ref/mod#go-mod-file-go][`go` directive]] specifies the minimum required version of the Go toolchain.
* Compiling a program
To compile a main package, run the following command in your shell:
$ go build [path-to-package-folder]
The current working directory is assumed if you omit the path argument.
A self-contained (statically linked) native executable will be created in the current working directory.
The name of the executable is inferred from the name of the directory that contains the main package in question (but with a `.exe` suffix on Windows).
.image https://go.dev/blog/5years/gophers5th.jpg 200 _
* Namecheck project: Hello World
1. Create, at the root of your project, a file named `main.go`:
namecheck
├── go.mod
└── main.go
2. Write a "Hello World" program in `main.go`; you can get it from the [[https://go.dev/play/p/S8HfNUCy13U][Go Playground]].
3. Compile the program.
4. Inspect the resulting executable with the `file` shell command.
5. Run the executable, and then delete it.
.image https://raw.githubusercontent.com/egonelbre/gophers/master/vector/superhero/gotham.svg 150 _
: for now, we'll code in this source file, but we'll reorganize our code later
: multiple compilers: gc (canonical one), gogcc, gollvm
* Compiling and executing a program in one fell swoop
If you just want to quickly execute the program without retaining an executable, run
$ go run main.go
which is roughly equivalent (on *nix systems) to
$ go build main.go
$ ./main
$ rm main
For various reasons, the `run` subcommand isn't appropriate for production, though.
.image https://miro.medium.com/max/4800/1*-bo7H329eM0O1eL_ASBVOA.jpeg 200 _
* Cross-compilation
An OS/architecture pair is known in the Go world as a [[https://pkg.go.dev/about#build-context][_build_context_]]. You can check your build context by running the following shell command:
$ go env GOOS GOARCH
darwin
amd64
By default, the Go compiler produces an executable for your own build context, but you can target a different one simply by setting a couple of environment variables:
$ GOOS=windows GOARCH=amd64 go build main.go
The following command lists all the build contexts supported by the compiler:
$ go tool dist list
.image https://go.dev/blog/store/gophers.jpg 150 _
* Namecheck project: cross-compiled Hello World
1. Pick a supported OS/architecture combination other than yours.
2. Compile your Hello World program for that target.
3. Inspect the resulting executable with the `file` shell command.
4. Delete the resulting executable.
.image https://raw.githubusercontent.com/egonelbre/gophers/master/vector/superhero/gotham.svg 150 _
* Keywords
Below is an exhaustive list of Go's keywords. Which ones are mysterious to you?
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
Note the absence of a `while` keyword; all loops are introduced by the `for` keyword.
Go also lacks keywords like `try`, `catch`, and `finally`: this should be no surprise if you know that Go has no exception system.
* Keywords
*defer* allows you to unconditionally execute some code at the end of a function.
It's useful for cleanup tasks, such as releasing _resources_ (i.e. something whose supply is finite and that requires management).
*range*, used in conjunction with `for`, allows you to iterate over various data structures.
*go* is used to spawn goroutines, which you can think of as lightweight threads.
*chan* and *select* are related to _channels_, which allow you to synchronize and communicate between goroutines.
*fallthrough* is a seldom useful keyword that lets you override the normal "breaking" behavior of Go's `switch` statement.
*goto* [[https://cs.opensource.google/go/go/+/refs/tags/go1.21.6:src/strings/strings.go;drc=132fae93b789ce512068ff4300c665b40635b74e;l=1118][has its uses]], but it's not for the average Go developer. Avoid it.
* Predeclared names
Go comes with several predeclared names accessible from anywhere in your code. We will cover some of them, but only as needed.
*Constants*
false true nil iota
*Built-in*types*
bool int rune uint byte float64 string
struct map chan
interface error
*Built-in*functions*
min max
make len cap new
append copy delete clear
panic recover
* Comments
[[https://go.dev/ref/spec#Comments][_Line_comments_]] start with a double slash and extend to the end of the line:
var foo = "foo" // this is a comment
[[https://go.dev/ref/spec#Comments][_General_comments_]] are delimited by `/*` and `*/`; they can be multiline and do not nest:
/*
this is
a general comment
*/
The documentation of a package is written as comments in the package's source file(s). For an example, see [[https://github.com/jub0bs/cors/blob/main/config.go]].
: won't talk too much about documentation in this first course
* Import path and package name
A package is identified by its [[https://go.dev/ref/spec#Import_declarations][_import_path_]], which must be globally unique.
Standard-library packages have import paths that are composed of one or more components delimited by slashes:
fmt
net/http
Other packages have import paths that take the form of [[https://www.youtube.com/watch?v=BNmxtp26I5s&t=310s][a domain followed by one or more components]]:
github.com/jub0bs/missilelauncher
The _name_ of a package corresponds to the last component of its import path:
fmt
http
missilelauncher
: "usually": the exception is for a package whose enclosing folder doesn't mach the package name; best avoided
: also, with versions of modules after v1, it's the second last path component: "rsc.io/quote/v3" => quote
* Package: the unit of compilation
A package is composed of one or more source files that are compiled together.
Gophers are free to break the source code of a package into multiple files because, in Go (as opposed to C-like languages), the order of package-level declarations doesn't matter.
Packages are indivisible: the smallest thing you can compile in Go is a whole package.
.image img/gopher-working-hard-to-move-packages-boxes-golang.png 250 _
: source: https://www.pngkit.com/png/full/412-4127445_gopher-working-hard-to-move-packages-boxes-golang.png
* Package: the unit of compilation (cont'd)
All of a package's source files
- start with the same _package_clause_, and
- are located in the same folder on the disk.
`fmt` is an example of a multi-file package. All its source files start with
package fmt
and are located in a folder named `fmt` somewhere within your Go installation:
fmt
├── doc.go
├── errors.go
├── format.go
├── print.go
└── scan.go
* Package documentation
The documentation of a locally installed package can be consulted at the command line with the `doc` subcommand, e.g.
$ go doc fmt
package fmt // import "fmt"
Package fmt implements formatted I/O with functions analogous to C's printf and
scanf. The format 'verbs' are derived from C's but are simpler.
-snip-
You can also ask for the documentation of a specific exported identifier:
$ go doc fmt Println
The documentation for standard-library packages is available online at [[https://pkg.go.dev/std]]. This website also allows you to discover useful third-party libraries and commands.
The documentation of some packages ([[https://pkg.go.dev/fmt#pkg-examples][`fmt`, for instance]]) features executable examples.
* Package: the unit of encapsulation
In Go, packages (as opposed to types) act as units of encapsulation.
There are only two access levels: a package-level identifier is either
- _exported_ (i.e. accessible from another package), or
- _unexported_ (i.e. only accessible within its own package).
Whether an identifier is exported depends on the case of its first letter:
package foo
var Bar = "Bar" // starts with an uppercase B: exported by package foo
type Baz struct { /* ... */ } // starts with an uppercase B: exported by package foo
const qux = 42 // starts with a lowercase q: unexported by package foo
func quux() { /* ... */ } // starts with a lowercase q: unexported by package foo
: you can tell just by looking at a package-level identifier whether it's public or private
* Importing packages
We'll cover two ways of importing packages: normal imports and named imports.
The [[https://pkg.go.dev/golang.org/x/tools/cmd/goimports][`goimports`]] utility (which your IDE invokes under the hood) takes care of
- adding missing imports,
- removing unused imports ([[https://cacm.acm.org/magazines/2022/5/260357-the-go-programming-language-and-environment/fulltext#body-4][which Go disallows in order to avoid bloat]]), and
- organizing imports in [[https://go.dev/wiki/CodeReviewComments#imports][a canonical way]].
import (
// standard-library packages
// other packages
)
.image https://go.dev/blog/store/gophers.jpg 200 _
: goimports should run every time you save a file in VS Code
* Normal imports
This is the most common form of import.
You used a normal import in your Hello-World program:
.play -edit src/helloworld.go
To access an identifier exported by a different package (`fmt`, here), you must qualify it using the package name as prefix (`fmt.Println`).
Importing a package without using it causes a compilation error! This was [[https://go.dev/talks/2016/refactor.article#TOC_2.][a conscious design decision]] to prevent code bloat.
* Named imports
Named imports allows you to use the imported package under a different name in the importing source file.
A named import is convenient when you perceive the package name as inappropriate, perhaps because it is too long:
import ml "github.com/jub0bs/missilelauncher"
Moreover, named imports are especially useful when your code imports multiple packages whose names conflict,
import "math/rand"
import crand "crypto/rand"
or when one of your source files uses multiple major versions of a _module_:
import "github.com/jub0bs/foo"
import foov2 "github.com/jub0bs/foo/v2"
: similar to `import numpy as np` in Python
* Blank imports (FYI)
A [[https://go.dev/wiki/CodeReviewComments#import-blank][blank import]] uses the blank identifier as package name:
import _ "github.com/go-sql-driver/mysql"
A blank import makes none of the imported package's exported identifiers available in the importing package.
The sole reason for using a blank import to import a package is the side effects carried out during [[https://go.dev/ref/spec#Package_initialization][the package's initialization]].
Blank imports play a part in the controversial _registration_pattern_, which is used in subpackages of the `image` package (such as [[https://cs.opensource.google/go/go/+/refs/tags/go1.21.6:src/image/png/reader.go;l=1059][`image/png`]]) and in third-party SQL drivers like [[https://github.com/go-sql-driver/mysql][github.com/go-sql-driver/mysql]].
Use blank imports if the libraries you import require you to, but do not emulate the registration pattern in your own packages.
: difficult to understand, based on shared global state
* Dot imports (FYI)
A [[https://go.dev/wiki/CodeReviewComments#import-dot][dot import]] allows you to access all the exported identifiers of the imported package without the need to qualify them:
.play -edit src/helloworld_dot.go
Dot imports can be convenient in test code (see [[https://cs.opensource.google/go/go/+/refs/tags/go1.18.1:src/strconv/quote_test.go;l=8][this example]]), but are best avoided in production code because
- they pollute the namespace of your source file,
- they obscure the provenance of identifiers.
: similar to Java's static imports
: used in conjunction with external test packages to pretend that we're still in the same package
: another example: https://cs.opensource.google/go/go/+/refs/tags/go1.21.6:src/net/http/client_test.go;l=20
* Basic types
*Booleans*
The type is named `bool` and comes with the usual operators: `&&` (AND), `||` (OR), `!` (NOT).
*Numeric*Types*
- signed integers: `int8`, `int16`, `int32`, `int64`, `int`
- unsigned integers: `uint8`, `uint16`, `uint32`, `uint64`, `uint`, `uintptr`
- floating-point numbers: `float32`, `float64`
- complex numbers: `complex64`, `complex128`
Integer types support the postfix form of increment & decrement operators: `i++`
*Strings*
A `string` is [[https://go.dev/blog/strings][a sequence of bytes usually representing a valid UTF-8 string]].
Strings literals are delimited either by double quotes (`"`) or backticks (```).
.image https://miro.medium.com/max/4800/1*OxWM0qyTBnb6WfSEw-T9sg.jpeg 200 _
: fixed-size integers
: the size of int, uint, and uintptr is either 32 or 64 bits: it depends on the compiler and the target architecture.
* Composites types
Go also provides composite types, which are composed of other existing types. Here are some examples:
*int // pointer
func (string) bool // function
[7]int // array
[]int // slice
map[string]string // map
struct {Lat string; Long string} // struct
interface{ String() string } // interface
chan error // channel
.image https://miro.medium.com/max/4800/1*OxWM0qyTBnb6WfSEw-T9sg.jpeg 200 _
* Every type has a zero value
In Go, unlike in C, there is no such thing as an uninitialized variable.
Every type, whether built-in or user-defined, has a default value called its _zero_value_.
When you declare a variable without initializing it, its value is the zero value of the variable's type:
var i int // the value of i is 0
var s string // the value of s is the empty string ""
.image https://raw.githubusercontent.com/egonelbre/gophers/master/vector/superhero/zorro.svg 150 _
Several types have `nil` as their zero value: pointers, functions, channels, interfaces, slices, and maps.
: in French: valeur vierge
: a reference type does not directly hold its contents. Instead a it holds a pointer to an underlying underlying data structure that holds the contents
* Comparability
Comparing a value to its type's zero value is always legal.
A type is said to be _comparable_ if *arbitrary* values of that type can be compared
for equality (with operator `==`) or inequality (with operator `!=`).
All basic types are comparable, but not all composite types are comparable;
for instance, functions, slices, and maps are not.
In some places (map keys, switch expressions, etc.), only comparable types can be used.
.image https://golangforall.com/assets/kanat.svg 200 _
* Type definitions
The `type` keyword lets you define a type based on some existing [[https://go.dev/ref/spec#Underlying_types][_underlying_type_]]:
type Celsius float64
type Fahrenheit float64
type Kelvin float64
`Celsius`, `Fahrenheit`, and `Kelvin` are _named_types_ all based on type `float64`.
The four types share the same zero value (`0`, in this case).
However, they are distinct types and are *not* interchangeable.
.image https://go.dev/blog/gopher/header.jpg 150 _
: You can only declare methods on defined types that you own.
: you can have type definitions anywhere, incl. inside functions
: - struct types useful for JSON encoding/decoding
: - interface types useful for asserting on behaviour
: few restrictions on the underlying type
* Type conversion
If two types are "compatible", an expression of one type can be [[https://go.dev/ref/spec#Conversions][converted]] to the other, either implicitly or explicitly.
However, Go requires many conversions from one type to another to be explicit.
.play -edit src/type_conversion.go /^//START/,/^//END/
Most type conversions are checked at compile time; [[https://go.dev/ref/spec#Conversions_from_slice_to_array_or_array_pointer][others only at run time]].
* Automatic memory management
The Go runtime, which includes a memory allocator and a [[https://en.wikipedia.org/wiki/Garbage_collection_(computer_science)][garbage collector (GC)]], manages memory for you. Be careful: memory leaks can nevertheless occur!
No need to explicitly allocate and free memory. Variables no longer referenced anywhere in the program become eligible for garbage collection. The garbage collector is efficient and rarely requires custom configuration.
Automatic memory management and the absence of pointer arithmetic contribute to making Go a memory-safe language: no risk of [[https://en.wikipedia.org/wiki/Dangling_pointer][dangling pointers]], [[https://en.wikipedia.org/wiki/Buffer_overflow][buffer overflows]], etc.
[[https://pkg.go.dev/unsafe][The `unsafe` package]] provides an escape hatch, but [[https://www.youtube.com/watch?v=PAAkCSZUG1c&t=830s][its general use is strongly discouraged]] because it voids many of the language's guarantees about memory.
.image https://raw.githubusercontent.com/egonelbre/gophers/master/vector/friends/heart-hug.svg 150 _
: GC much simpler to configure than in Java
: unlike in C, it's perfectly OK to return the address of a local variable
* Variable declaration
You can declare variables at the package level or locally within a function. A _local_variable_ *must* be used, or compilation will fail.
.play -edit src/variables.go
Variable names (and other identifiers in Go) [[https://go.dev/ref/spec#Identifiers][must]] start with a Unicode letter followed by an arbitrary number of Unicode letters and Unicode digits.
Go's declaration syntax departs from C's in many ways. Rob Pike clarified the motivations behind this departure in [[https://go.dev/blog/declaration-syntax][a post entitled _Go's_Declaration_Syntax_]].
Two alternative declaration syntaxes exist: the `var` keyword and the `:=` operator.
* Variable declaration with var
The `var` keyword affords maximum flexibility for declaring variables:
var s1 string = "Hello, World!"
If the variable's type can be inferred from the right-hand side, you can omit the type:
var s1 = "Hello, World!"
If the variable's initial value doesn't matter or should be the type's zero value, you can simply omit the equal sign and right-hand-side expression:
var s1 string
However, you cannot omit both the type and the right-hand-side expression, because the compiler doesn't have enough information to determine the variable's type:
var s1 // compilation error
* Short variable declaration with :=
The `:=` operator lets you declare _and_ initialize a variable, whose type is inferred from the right-hand-side expression:
msg := "Hello, World"
This [[https://go.dev/ref/spec#Short_variable_declarations][short-variable-declaration syntax]] makes Go feel a bit like a dynamic language!
If the expression is compatible with multiple types, the compiler uses a default type.
For instance, the default type for integer constants is `int`:
.play -edit src/integer_default_type.go /^//START/,/^//END/
* Short variable declaration with := (cont'd)
The `:=` operator is convenient for assigning the results of a function to variables:
i, err := strconv.Atoi("42") // declares i and err
The `:=` operator allows you to perform [[https://go.dev/doc/effective_go#redeclaration][a mixture of declaration and assignment]]:
i, err := strconv.Atoi("42") // declares i and err
j, err := strconv.Atoi("96") // declares j, but only updates err
However, the `:=` operator must introduce at least one new variable:
i, err := strconv.Atoi("42")
i, err := strconv.Atoi("96") // compilation error: no new variables on left side of :=
If you only care about some of the results, assign the others to the _blank_identifier_:
_, err := strconv.Atoi(s) // declares err, but discards the first result
* Inadvertent variable shadowing
This mixture of declaration and assignment can lead you to accidentally declare a new variable rather than update an existing one declared in an enclosing scope.
Such inadvertent [[https://en.wikipedia.org/wiki/Variable_shadowing][_variable_shadowing_]] can be a source of [[https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/shadow#hdr-Analyzer_shadow][subtle bugs]]:
func BadRead(f *os.File, buf []byte) error {
var err error
for {
n, err := f.Read(buf) // shadows the function variable 'err'
if err != nil {
break // causes return of wrong value
}
foo(buf)
}
return err
}
(Don't worry if you cannot follow this example yet. Revisit it later.)
When you use the `:=` operator, always ask yourself whether you're declaring new variables or updating existing ones.
* Naming conventions for variables
You should [[https://go.dev/wiki/CodeReviewComments#variable-names][strive for conciseness]]; [[https://go.dev/talks/2014/names.slide#4][the smaller the scope, the shorter the name]].
var index int // too verbose?
var i int // likely preferable
Use lower camel case for local variables and unexported package-level variables:
var maxOutstanding int
var nbOfVisits uint
Use upper camel case (a.k.a. Pascal case) for exported package-level variables:
var UnknownAvailabilityError = errors.new("namecheck: unknown availability")
Aside from the _blank_identifier_, don't use underscores in variable names.
: same conventions with constants
: Go treats all characters in any of the Letter categories Lu, Ll, Lt, Lm, or Lo as Unicode letters
: ...and those in the Number category Nd as Unicode digits.
: _ is considered a letter
: also https://go.dev/wiki/CodeReviewComments#initialisms
* Favor the := operator in most cases
Because Go has two syntaxes for declaring variables, you may be wondering which one to use in a given situation...
Convention dictactes that the `:=` operator be used whenever possible, *except* when the initial value doesn't matter or simply should be the type's zero value.
finished := false // possible but unidiomatic
var finished bool // better
.image https://raw.githubusercontent.com/egonelbre/gophers/master/vector/fairy-tale/sage.svg 200 _
* Resort to the var keyword if needed
In some cases, you have no option but to use the `var` keyword...
*To*declare*a*package-level*variable*
package foo
// maxConcurrent := 16 // compilation error: non-declaration statement outside function body
var maxConcurrent = 16 // works fine
*To*declare*a*variable*whose*desired*type*cannot*be*inferred*
type Fahrenheit float64
func main() {
// freezing := 32 // inferred type: int 😞
// freezing := Fahrenheit(32) // viable but unidiomatic
var freezing Fahrenheit = 32 // type Fahrenheit 🙂
fmt.Println(freezing)
}
: a nil value carries no type information (could be a map, a function, a slice, a pointer)
* Namecheck project: validation of GitHub usernames
In your `main` function, do the following:
1. Assign your prospective username to a string variable named `username`.
2. Which variable declaration syntax did you choose? Justify your choice.
3. Print the username variable to the screen.
.image https://raw.githubusercontent.com/egonelbre/gophers/master/vector/superhero/gotham.svg 200 _
* Constants
The `const` keyword lets you declare constants, which are values fixed at compile time:
const freezing Farenheit = 32
A constant may be untyped but can only be either a number, a boolean, or a string.
The constant expression can be of a higher precision than variables:
const Pi = 3.14159265358979323846264338327950288419716939937510582097494459
For convenience, Go allows you to group declarations of related constants in blocks, by "factorizing" the `const` keyword:
const (
width int = 480
height int = 360
)
Go constants are actually [[https://go.dev/blog/constants][interesting in their own right]]; they simplify Gophers' life but [[https://www.youtube.com/watch?v=rFejpH_tAHM&t=966s][are actually a complex beast under the hood]].
: declaration blocks: as well as types, variables, and imports
: The right-hand-side expression must itself be constant (i.e. evaluatable by the compiler)
: no function calls allowed on right-hand side
: allow optimisations by the compiler
* iota: the constant generator
The predeclared identifier [[https://pkg.go.dev/builtin#iota][`iota`]] is Go's [[https://go.dev/ref/spec#Iota][constant generator]].
In a constant block, the value of `iota` is incremented (from 0) on each successive line:
const (
_ = iota // ignore first value by assigning to blank identifier
KB ByteSize = 1 << (10 * iota)
MB
GB
TB
PB
EB
ZB
YB
)
Lines that lack a type and an expression implicitly reuse those of the preceding line (within the same constant block) that has a type and an expression.
* Using iota for declaring enums
Go has no [[https://en.wikipedia.org/wiki/Enumerated_type][enums]], but you can declare a set of related constants as a [[https://go.dev/play/p/fMT2U4xnydk][type-unsafe]] semblance of an enum. `iota` is [[https://go.dev/doc/effective_go#constants][useful]] for that:
type Shape int
const (
Rock Shape = iota
Paper
Scissors
)
See [[https://pkg.go.dev/time#Month][`time.Month`]] and [[https://pkg.go.dev/net/http#SameSite][`http.SameSite`]] for examples from the standard library.
: typically, defined type whose underlying type is int
: no automatic String method
* Using iota for declaring bit fields
`iota` is also convenient for declaring [[https://en.wikipedia.org/wiki/Bit_field][_bit_fields_]], as in [[https://pkg.go.dev/log#pkg-constants][the `log` package]]:
const (
Ldate = 1 << iota // the date in the local time zone: 2009/01/23
Ltime // the time in the local time zone: 01:23:23
Lmicroseconds // microsecond resolution: 01:23:23.123123. assumes Ltime.
Llongfile // full file name and line number: /a/b/c/d.go:23
// etc.
)
Those bit fields can then act as flags and be combined via bitwise integer operations:
log.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds | log.Llongfile)
See also [[https://pkg.go.dev/io/fs#FileMode][`fs.FileMode`]] for another example from the standard library.
* If statements
Unlike in C, the condition must be of type `bool` and needs not be enclosed in parens.
However, braces around the "if" branch are mandatory.
.play -edit src/if_simple.go /^//START/,/^//END/
A [[https://go.dev/ref/spec#Statements][_simple_statement_]] (usually a short variable declaration) can precede the condition:
.play -edit src/if_short_variable_decl.go /^//START/,/^//END/
Because the scope of such variables is restricted to the if(-else) statement, this syntax frees you to reuse the same variable name ("err", in this case).
: mandatory braces: no dangling-else problem like in C, JS, etc.
: short-var-decl: useful for error handling
* If-else statements
Braces around the body of an "else" branch are also mandatory.
.play -edit src/if_else.go /^//START/,/^//END/
Note that Go has no conditional ternary operator.
The `else` keyword is rarely used in Go. Long if-else chains are considered non-idiomatic, and can often be advantageously replaced by a "tagless" switch statement.
* "Tagless" (expression-less) switch
This special form of a switch statement lacks a switch expression.
.play -edit src/tagless_switch.go /^//START/,/^//END/
This form of `switch` statement is preferred to a long if-else chain.
* More general switch statement
The switch expression, whose type must be comparable, is evaluated once.
The case expressions (not necessarily constants), are evaluated left-to-right and top-to-bottom and tested for equality against the switch expression until a match is found.
The case clause of the first match gets executed. If no match is found, the default case clause (if any) gets executed.
.play -edit src/switch.go /^//START/,/^//END/
Unlike in C and other languages, no `break` keyword is required at the end of case clauses. Use the `fallthrough` keyword if needed (which is rare).
: A short-variable-declaration statement can precede the switch condition.
: The default clause can occur at any place among the the normal cases.
: There is another form of switch known as _type_switch_, which you can ignore for now.
* Namecheck project: validation of GitHub usernames
A username is deemed [[https://docs.github.com/en/site-policy/other-site-policies/github-username-policy][acceptable by GitHub]] if
- it does not start/end with a hyphen and does not contain two consecutive hyphens;
- it contains between 3 and 39 alphanumeric or hyphen characters.
In your `main` function, do the following:
1. Using functions from the [[https://pkg.go.dev/strings][strings]] and [[https://pkg.go.dev/regexp][regexp]] packages, check whether your username follows both rules. Ignore any error for the time being; more about error handling later.
2. Only if your username follows both rules, print that username to the screen.
.image https://raw.githubusercontent.com/egonelbre/gophers/master/vector/superhero/gotham.svg 150 _
: note: regexp compilation is CPU-intensive
* Namecheck project: validation of GitHub usernames (cont'd)