-
Notifications
You must be signed in to change notification settings - Fork 1
/
03-fundamentals.slide
553 lines (358 loc) · 12 KB
/
03-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
# Fundamentals #2
Course Go
Tags: golang, go
## Outline
- Interfaces
- Errors
- Arrays
- Slices
- Maps
- Range
## Keywords
```
break case chan const continue
default defer else fallthrough for
func go goto if import
interface map package range return
select struct switch type var
```
The first two lectures already covered:
```
break case const continue
default defer else fallthrough for
func goto if import
package return
struct switch type var
```
This one goes over:
```
interface map range
```
## Operators and characters with special meaning
```
+ & += &= && == != ( )
- | -= |= || < <= [ ]
## ^ ##= ^= <- > >= { }
/ << /= <<= ++ = := , ;
% >> %= >>= -- ! ... . :
&^ &^=
```
## Interfaces
## Interfaces
- Set of methods required to implement such interface
- Declared via `interface` keyword:
```
type XI interface {
method1()
method2(int) int
}
```
- Interface type — variable of interface type, can hold any value implementing an interface
- Variable of interface type *I* can hold any value _implementing_ *I*
[Go Data Structures: Interfaces by Russ Cox](https://research.swtch.com/interfaces)
## Implementing an interface
- AKA _satisfying_ an interface
- Has no special keyword
- No `implements` or anything similar
- Instead, every type which implements all interface's methods automatically satisfies such interface
## Satisfying an interface
.play assets/lecture-03/interfaces/satisfy.go
## Embedding other interface(s)
- Interfaces can be embedded
- Order does not matter
```
type Calculator interface {
Adder
Subtracter
Multiplier
Divider
display() string
}
```
## Circular embedding
- Forbidden, detected by compiler
```
type I1 interface {
I2
method_i1()
}
type I2 interface {
I3
method_i2()
}
type I3 interface {
I1
method_i3()
}
```
## Declaration of two interfaces
.code assets/lecture-03/interfaces/interfaces.go
## Missing interface implementation
.play assets/lecture-03/interfaces/missing-implementation.go /^type OpenShape/,/END OMIT/
## Implementation of an interface
.play assets/lecture-03/interfaces/implementation.go /^type OpenShape/,/END OMIT/
## Multiple implementations of a single interface (1/2)
.play assets/lecture-03/interfaces/multiple-implementations.go /START OMIT/,/MIDDLE OMIT/
## Multiple implementations of a single interface (2/2)
.play assets/lecture-03/interfaces/multiple-implementations.go /MIDDLE OMIT/,/END OMIT/
## Empty interface
- Is automatically satisfied by any type
- Value of any type can be assigned to such interface type variable
.play assets/lecture-03/interfaces/empty.go
## Type any
- Alias for empty interface
```
type any interface{}
```
- Used in the standard library in many places
## nil interface
- *Static type* known by compiler, from the declaration
- Interface type value consists of two components: dynamic type and dynamic value
- *Dynamic type* - the type of the assigned _value_
- *Dynamic value* - the actual value assigned
- Where's the problem?
- Interface type value is `nil` if both dynamic value *and* dynamic type are `nil`
- Sometimes we get the impression that `nil != nil`
[Russ Cox: Interfaces](https://research.swtch.com/interfaces)
## nil interface
.play assets/lecture-03/interfaces/riddle.go /START OMIT/,/END OMIT/
## nil interface
.play assets/lecture-03/interfaces/nil.go
## Type assertions
- Access to an interface value's underlying concrete value
```
variable := iface.(Type)
```
- Checks that the interface value `iface` holds the concrete type `Type`
- If check fails, panics
- Assigns the underlying `Type` value to the variable `variable`.
```
variable, ok := iface.(Type)
```
- Checks that the interface value `iface` holds the concrete type `Type`
- If check fails, `variable` will contain zero value and `ok` will be `false`
- If check passed, assign the underlying `Type` value to the variable `variable`, `ok` will be `true`
- Also knows as "comma ok idiom"
## Type assertions
.play assets/lecture-03/interfaces/assertions.go
## Type assertions
.play assets/lecture-03/interfaces/server-error-assertions.go
## Errors
## Errors
- Error is a built-in type
- And is also an interface
- Errors are handled as values
- I.e. you won't find any exceptions here
```
type error interface {
Error() string
}
```
[builtin.go](https://cs.opensource.google/go/go/+/master:src/builtin/builtin.go;l=308)
## Error handling
[Go Blog: Error handling and Go](https://go.dev/blog/error-handling-and-go)
.play assets/lecture-03/errors/errors.go
## Wrapping errors
- Errors can be wrapped using `fmt.Errorf`
- Errors can be then `unwrapped` to obtain wrapped errors
- Either by calling `errors.Unwrap` directly
- Or by `errors.Is` and `errors.As` functions
[errors package](https://pkg.go.dev/errors)
## Wrapping errors
.play assets/lecture-03/errors/wrapping.go /START OMIT/,/END OMIT/
## Sentinel errors
.play assets/lecture-03/errors/sentinel.go /START OMIT/,/END OMIT/
## Custom errors
.code assets/lecture-03/errors/custom.go /START OMIT/,/MIDDLE OMIT/
## Custom errors
.play assets/lecture-03/errors/custom.go /MIDDLE OMIT/,/END OMIT/
## Line of sight
- [Line of sight by Mat Ryer](https://medium.com/@matryer/line-of-sight-in-code-186dd7cdea88)
- About idiomatic and easy to comprehend Go code
- "Happy path" on the left (one column)
- No nest of indented braces for "happy path"
- Exit early
- No else returns style statements (`golint` is able to detect it)
- "Happy return" at the very last line
[Uncyclopedia: Go](https://en.uncyclopedia.co/wiki/Go_%28programming_language%29)
## Panic
- So errors are nice
- What about the panics?
.play assets/lecture-03/panic/panic.go
## Recover
.play assets/lecture-03/panic/recover.go
[Go Blog: Defer, Panic, and Recover](https://go.dev/blog/defer-panic-and-recover)
## Arrays
## Arrays
- Basic data type in the Go programming language
- All array items have the same type
- Unless you use `interface{}` to allow _dynamic typing behaviour_
- Type of an array is derived from the type of items **and** the array's size
- Unlike slices
- Index in range *<0,length)*
- Array items are indexed via `[]`
- As in most other languages
## Basic operations with arrays
.play assets/lecture-03/arrays/arrays.go
## Matrix
- Arrays can be nested
.play assets/lecture-03/arrays/matrix.go
## Array copy
- Unlike slices, arrays are copied
.play assets/lecture-03/arrays/reassignment.go
## Array index out of bounds
.play assets/lecture-03/arrays/bounds.go
.play assets/lecture-03/arrays/panic.go
## Slices
## Slices
- Proper data type in the Go
- Slices are used more often than _plain old arrays_
- Arrays themselves are actually almost never used
- Arrays only serve as the foundation for slices
- Type of slice is derived from the type of it's items
- Internally, a slice is triple:
- **Pointer** to the first element (start of the underlying array)
- **Length** of the array
- **Capacity** of the array
- "Slice operator" `[from:to]`
- `append` function to add a new element to slice (complicated internally)
## Slicing
.play assets/lecture-03/slices/slices.go /START OMIT/,/END OMIT/
[Go Blog: slice usage and internals](https://go.dev/blog/slices/intro)
## Slices and arrays as data source for them
- Slice can be created from any array
- The slice does not contain any data, just a pointer to array element
- Any modification of a slice element is reflected in the array as well
## Slices and arrays as data source for them
.play assets/lecture-03/slices/modifications.go /START OMIT/,/END OMIT/
## Slice from slice
.play assets/lecture-03/slices/slicing.go /START OMIT/,/END OMIT/
## append function
- The function `append` returns a new slice
- Always assign the output of append to the same slice
- The capacity of new slice can be increased
- Realloc magic inside!
.play assets/lecture-03/slices/append.go /START OMIT/,/END OMIT/
## make function
- Allows to create slices with preallocated size
- Takes up to three arguments. Mind the order!
- Type of the slice
- Length
- Capacity (optional)
.play assets/lecture-03/slices/make.go /START OMIT/,/END OMIT/
## Variadic functions
.play assets/lecture-03/slices/variadic-func.go /START OMIT/,/END OMIT/
## Maps
## Maps
- AKA associative array, hash map, or dictionary
- Data structure for key-value pairs
- Default value is nil:
```
var m1 map[int]string
```
- New, empty map:
```
var m2 = map[int]string{}
var m2 map[int]string = make(map[int]string)
m3 := make(map[int]string) // most idiomatic
```
[Go Blog: Go maps in action](https://go.dev/blog/maps)
## Map operations
- Three basic operations: add/put, get, and delete
- Add or replace an item in a map:
```
m3[0] = "zero"
m3[1] = "one"
m3[2] = "two"
```
- Retrieve a value from a map:
```
m3[2] // 2 is the key
```
- Delete key-value pair from a map
```
delete(m3, 0) // 0 is the key
```
## Unitialized map
- Once again, default value for map is `nil`
- Reading return the default value
- Writing is forbidden
.play assets/lecture-03/maps/nil.go
## Initialized map
- Make can help you specify expected number of elements for the map
.play assets/lecture-03/maps/initialized.go
## Map literals
.play assets/lecture-03/maps/literals.go
## Structs as values
.play assets/lecture-03/maps/struct-values.go /START OMIT/,/END OMIT/
## Struct as both value and key
.code assets/lecture-03/maps/structs.go /START OMIT/,/MIDDLE OMIT/
## Struct as both value and key (cont.)
.play assets/lecture-03/maps/structs.go /MIDDLE OMIT/,/END OMIT/
## Non-existent values
.play assets/lecture-03/maps/nonexistent.go
So how can we differentiate between actual default value and missing key?
## Reading items from map
.play assets/lecture-03/maps/reading.go /START OMIT/,/END OMIT/
## Deleting items from map
- built-in `delete` function
.play assets/lecture-03/maps/deleting.go /START OMIT/,/MIDDLE OMIT/
## Deleting items from map (cont.)
.play assets/lecture-03/maps/deleting.go /MIDDLE OMIT/,/END OMIT/
## Sets
- There are no sets in Go
- However, they can be easily simulated using maps
- A `struct{}` type can be used for values
- Consumes no memory
```
map[key_type]struct{}
```
- Or `bool`
- Takes up memory
- "Cleaner" access
```
if set[key] { // returns bool
...
}
```
## Range
## Loops and the range clause
- Other than the three types of loops presented in the previous fundamentals lecture:
- Classic C-style for loop
- While with condition
- Endless while
- A fourth type exists:
- For loop with range clause
- This `range` clause helps us iterate over array items, slice items, map pairs etc.
- Provides an item index as well
- Enumeration
## Iterating over integers
.play assets/lecture-03/range/ints.go
## Iterating over arrays
- First item stores the index, second stores the values
.play assets/lecture-03/range/arrays.go /START OMIT/,/END OMIT/
## Iterating over slices
- Works the same way as range with arrays
.play assets/lecture-03/range/slices.go /START OMIT/,/END OMIT/
## Iterating over strings
.play assets/lecture-03/range/strings.go
## Iterating over maps
- Note that the order of the key-value pairs is undeterministic
.play assets/lecture-03/range/maps.go
## Iterators
- Iterates elements one-by-one
- `yield` function
- Required signatures:
```
func(func() bool)
func(func(K) bool)
func(func(K, V) bool)
```
- Handy generic shortcuts:
```
Seq[V any] func(yield func(V) bool)
Seq2[K, V any] func(yield func(K, V) bool)
```
[Package: iter](https://pkg.go.dev/iter)
## Iterator example
.play assets/lecture-03/range/iterator.go /START OMIT/,/END OMIT/