-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathintro-to-go.slide
1274 lines (825 loc) · 30.2 KB
/
intro-to-go.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
Go for Perl Programmers (or non-Perl Programmers)
Dave Rolsky
[[mailto:[email protected]][[email protected]]]
[[http://blog.urth.org/][blog.urth.org]]
* License
.html license.html
* Introductions
- Your name
- What sort of programming you do (languages, tools, products)
- Why you're interested in Go
* Are You Prepared?
- Do you have a computer?
- ... with Go 1.18 installed?
- ... and your text editor of choice?
- ... and the git repos for this class?
* Goals for This Class
- Provide a broad overview of Go
- Touch on many parts of the language
- *We are not* covering the language in depth
- This is a first step, not the final step
* Go Principles
- There's (mostly) one way to do it
- There's definitely just one way to format it
- Minimize repetition and clutter
- Very strong source compatibility - new versions of Go 1.x will not break existing code
- All the information needed to compile a program is in the source
- No Makefiles, header files, etc.
* Hello, World
.play code/hello-world1/hello-world1.go
* Hello, World Again
.play code/hello-world2/hello-world2.go
* Toolchain and the Ecosystem
* $GOPATH
- This used to be a thing
- Still mentioned in older docs
* Source Code Organization
- Source is identified by a repo path
- `~/projects/github.com/google/go-github/github`
- `~/projects/github.com/pborman/uuid`
- Both your code and third-party packages
* Starting a New Go Project
- Pick a repo
- Make a directory like `~/projects/my-project`
- Run `go`mod`init`github.com/me/project`
- Hack, hack, hack
* Packages, Repos, and Paths
.play code/uuid-example/uuid-example.go
> cd projects
> mkdir -p github.com/autarch
> cd github.com/autarch
> git clone https://github.com/autarch/intro-to-go-class-code
> cd code/uuid-example
> go get
- Downloads `uuid` package to local module cache.
* The Toolchain
- The `go` program does most of the work
- `go`get` - download packages
- `go`build` - create an executable for specified package in place
- `go`install` - create an executable for specified package and put it in `$HOME/go/bin`
- `go`run` - run the specified code
- `go`test` - run tests for the specified package
- `go`fmt` - runs `gofmt` tool on specified package
- `go`vet` - runs `govet` tool on specified package
- `go`mod`init` - start a new project
* More Tools
.link https://github.com/golangci/golangci-lint
- Runs many linting/formatting tools on your code in parallel
.link https://pkg.go.dev/golang.org/x/tools/cmd/goimports?tab=doc
- Runs `go`fmt` and cleans up import list
* Links to Open Now
.link https://pkg.go.dev/std Standard library docs - https://pkg.go.dev/std
.link https://go.dev/doc/effective_go Effective Go - https://go.dev/doc/effective_go
.link https://go.dev/ref/spec Language Spec - https://go.dev/ref/spec
* From Zero to Code
* Our First Goal
- Learn enough of the language to write a "real" program
- (Not "Hello, World")
* Syntax in a Nutshell
- It's mostly like C, Perl, Ruby, JavaScript, and many others
- No semi-colons at end of line
- Variable assignment with `=`
- Comparisons with `==`, `<`, `>`, etc.
- Math operators are `+`, `-`, `*`, `/`, etc.
- Comments are `//` (single line) or `/*`delimited`*/`
- `if` statements do not use parens
- If we don't cover it explicitly, assume it's what you'd think it would be
* Go Naming Conventions
- Variables and functions: CamelCase and camelCase, not snake_case
- Constants: same thing
- If function, variable, or constant starts with a capital letter, it's exported
- Same for package-scoped variables
package foo
var Foo = 42
var bar = 84
const Pi = 3.14
const realPi = 3.14159
func Exported() { ... }
func internalOnly() { ... }
* Variable Declarations
- Several ways to declare
- `var`foo`string`=`"bar"`
- Type can be omitted if the compiler can figure it out
- `var`foo`=`"bar"`
- `var` name, type, optional assignment
- `foo`:=`42` - "short variable declaration"
- short declaration initializes and infers type
// Go knows this is an int
foo := 42
// Go looks at the return value of uuid.New() - it's a uuid.UUID
id := uuid.New()
* Variable Initialization
- Variables always have a sane "zero" value
- Actual `0` for numbers
- An empty string for strings
- An empty struct
- Etc.
* Unused Variables
- Unused variables cause compilation to fail!
- This may surprise you during the exercises
* Scope and Re-declaration
- Variables are always lexically scoped from where they're declared
- The lexical scope for control structures is the structure block (more on that later)
- Can redeclare variables declared with short declaration
- Can only-redeclare if we're also creating a new var
* Declaration Examples
.play code/declarations/redeclare-ok.go
* Declaration Examples
.play code/declarations/redeclare-bad.go
* Constants
- Declared very similarly to variables:
const answer = 42
const pi float64 = 22/7
- Can also declare multiple constants:
const (
answer = 42
pi float64 = 22 / 7
)
* Constants and iota
- Can assign `iota` to a constant - each assignment increments `iota`
.play code/constants/iota.go
* Built-in Types
- boolean - `true` and `false`
- `uint`, `uint8`, 16, 32, 64
- `int`, `int8`, 16, 32, 64
- `float32`, `float64`
- `complex64`, `complex128`
- `string` - Unicode everywhere - ``"foo, 酒廊"``
- `rune` - one Unicode code point - `'廊'`
- `byte` - a single 8-bit value
- `[4]string` - array of 4 strings
- `[]string` - slice of strings
- structs, pointers, maps, channels, interfaces, function types - all covered later
* Working With Arrays and Slices
- They are 0-indexed
- Use the `len` built-in to check the length of an array or slice
size := len(array)
- Access elements with square brackets:
val0 := array[0]
- Accessing a value out of bounds causes a runtime panic!
- We'll cover creating, pushing, slicing, and more later
* Function Declarations
- Functions that return values need a `return` statement
func funcName(arg1 string, arg2 int64) string {
...
return str
}
func NoArgs() (string, error) {
...
return str, err
}
- Functions that do not return values can still contain a bare `return`
func AllArgsTheSame(arg1, arg2, arg3 string) {
...
return
}
func variadicArgs(args ...int64) {
...
return
}
* Calling Functions
noReturn()
foo := returnsValue()
foo, bar, baz := returnsSeveralValues()
foo = requiresArguments(arg1, arg2)
// The blank identifier (_) ignores a value
foo, _, baz = returnsSeveralValues()
// Function is in another package
dir, err := os.Getwd()
* Package declarations
- Every go file must declare a package
- Multiple files can declare the same package (and this is common)
- All the files in one directory should share a single package
- The package name must match the directory's name
- `github.com/autarch/project/path/to/foo` has a package named `foo`
- Go style package names are lower case without underscores
- Any unicode character is valid
package математический
* Package main and func main
- The `main` package is used to create an executable
- If a directory named `my-great-program` contains a file like `main.go`:
package main
func main() {
...
}
- When you run `go`build` you get an executable named `my-great-program`
* Importing
- Core packages are imported by name (without a repo):
package main
import "os"
- Can import many packages at once:
package main
import (
"encode/json"
"log"
"os"
)
- Package names are the last part of the path, so the `encode/json` is referred to in code as `json`:
json.NewDecoder() // not encode/json.NewDecoder()
* Printing Output
- We've seen `log` (`log.Print()`) and `os` (`os.Stdout.WriteString()`)
- Can also use `fmt`
.play code/fmt-example/fmt-example.go
* The os Package
- Does a lot of stuff, including syscalls (`chdir`, `symlink`, etc.)
- Defines file and process structs
* Getting Positional Command Line Args
- Use `os.Args`:
.play code/os-args-example/os-args-example.go
- Argument 0 is the program name
* Checking Errors
- Go has exceptions, but they're not used for APIs
- Used internally or for unrecoverable errors
- Errors are returned as `Error` type values
- `Error` values stringify
- If there was no error the value is `nil`
dir, err := os.Getwd()
if err != nil {
log.Fatal(err) // Prints a log message and then calls os.Exit(1)
}
* Reading Command Line Arguments
- Use `strconv.ParseInt`:
import (
"os"
"strconv"
)
arg1, err := strconv.ParseInt(os.Args[1], 10, 64)
- `strconv.ParseInt` takes the string to parse, the base (2, 10, etc.), and the bit size (32, 64)
- It returns an int64 and an error
- If it can't convert it then it returns an error
* If/Else
- `if` does not use parens
if foo > 42 {
...
} else if bar < 12 {
...
} else {
...
}
* Compound if Statement
- Very, very common Go idiom:
if err := someOperation(); err != nil {
log.Fatal(err)
}
- The `err` variable is only in scope for the `if` statement and its block
* The log Package
- `log.Print(msg)` - prints `msg`
- `log.Fatal(msg)` - calls `log.Print(msg)` and then calls `os.Exit(1)`
- You will use this in the first exercise
- `log.Panic(msg)` - logs `log.Print(msg)` and then calls `panic()`
- Output from `log` goes to standard error by default, but you can change that
* String Concatenation
- Concatenate strings with `+`:
string3 := string1 + string2
log.Print(arg + " is not a number")
* Exercise 1
- `cd`$intro-to-go-class-exercises/1-calc/calc`
- Open `calc.go` in your editor of choice
- Read the instructions
* More Types
* Strings
- Double quoted - ``"some text goes here"``
- Backticks for multi-line strings:
long := `
This is a long chunk of text.
That first newline is included, as is the last.
`
- Backtick strings are "raw" - backslashes have no special meaning
"\n" != `\n`
- String concatenation is done with `+`
str := other + " suffix"
* String Operations
- Get the length in bytes with `len(s)`
- Use `unicode/utf8` and call `utf8.RuneCountInString(s)` to count runes (aka characters)
- Many, many functions in the `strings` package
- `strings.Trim()`, `strings.Split()`, `strings.Index()` and many more
* Arrays and Slices
- Arrays are fixed-length, declared in advance, passed by value
- Arrays (and slices) are initialized to a sane "zero" value if not populated
// Every element is 0
var b [42]byte
- Slices are like arrays but do not require a length, passed by reference
var s []string
- Can also populate when declaring and take references to existing slices (or arrays)
s := []string{"a", "slice", "of", "strings"}
t := s[0:2]
// t is {"a", "slice"}
s[0] = "the"
// t is {"the", "slice"}
* Arrays and Slice Example
.play code/arrays/arrays.go
* The make() Built-in
- `make(Type,`Length)` returns a new slice
.play code/arrays/make.go
* Appending to a Slice
.play code/arrays/append.go
* Iterating Over a Slice
.play code/arrays/iterate.go
* Sorting Slices
.play code/arrays/sort.go
- You can sort other types with the `sort.Slice` and `sort.SliceStable` funcs
* Maps
- Called hashes or dictionaries in many languages
- Key/value mapping
- In Go, key can be any type that supports comparisons with `==` and `!=`
- Can get the length with `len(m)` just like arrays
* Maps Example
.play code/maps/maps.go
* Iterating Over Maps
.play code/maps/iterate.go
* Exercise 2
- `cd`$intro-to-go-class-exercises/2-count-strings/count-strings/count-strings.go`
- Open `count-strings.go` in your editor of choice
- Read the instructions
* Making Your Own Types
- Types are declared with `type`
- You can "alias" built-in types
package user
type UserID uint64
func UserByID(id UserID) {
...
}
- This adds implicit documentation
- Also does type enforcement (`uint64` != `UserID`)
* Type Conversion
- You can convert types with `type(value)`:
.play code/types/types.go
* Type Conversion
- Type conversion is explicit
.play code/types/error.go
- This prevents you from using a `CompanyID` as a `UserID` even though they're both `uint64` under the hood!
* Struct Types
type Person struct {
firstName string
lastName string
}
- The first character of a struct member determines public vs private
- This is just like type names and function names inside a package
- A struct can contain anything - arrays, maps, other structs:
type Account struct { ... }
type Address struct { ... }
type Person struct {
firstName string
lastName string
accounts []Account
addresses map[string]Address
}
* Working With Structs
.play code/types/person.go
* The nil Value
- `nil` is the empty value for pointers, slices, maps, function types, and channels
var foo map[string]int
if foo == nil { ... }
- We will cover function types and channels later
- You often need to check whether a value is `nil` in Go
* Making Your Own Packages
- Packages are imported by their full path - `github.com/pborman/uuid`
- Package *names* are the final part of the path
- Inside that directory, all files must start with `package`uuid` (well, not quite all)
- The actual file names are irrelevant
* Package File Layout Example
github.com/autarch/code/packages
└── user
├── cache.go
├── user.go
└── user_test.go
- Imported as `github.com/autarch/code/packages/user`
- Can call functions like `user.New(...)`
- Every `.go` file starts with `package`user`
- We'll cover `*_test.go` files later
* Exercise 3
- `cd`$intro-to-go-class-exercises/3-basic-user-package/user`
- Open `user.go` in your editor of choice
- Read the instructions
* Pointers in Go
- `&` takes a pointer
- `*` de-references
- Pointers are somewhat automatic
- Can (mostly) be used just like the type they point to
- But you must be explicit with function arguments
* Taking a Pointer
.play code/pointers/pointers.go
* Function Takes a Pointer
.play code/pointers/pointers2.go
* Function Returns a Pointer
.play code/pointers/pointers3.go
* Making a Pointer to a Struct in Place
.play code/pointers/pointers4.go
* Why Bother?
- Can be more efficient
- Use a pointer for structs with large amounts of data
- Lets you modify the caller's value
* Modifying The Caller's Value
.play code/pointers/pointers5.go
* Passing Functions and Function Types
- In Go, functions are first class
- Can assign a function to a variable
- Can pass them to other functions and return them from functions
- Can (and must) specify them as types to pass them
- Can define an anonymous literal function inline
* Function Passing Example
.play code/function-types/functions.go
* Function Literals are Closures
- A closure "captures" the state of variables in the scope where it's defined
* Closure Example
- What does this program print?
.play code/function-types/closures.go
* Defer
- The `defer` keyword says that a function (or method) should be executed later
- Later is right before the surrounding function exits
- Works with named functions, methods, and anonymous functions
- Called in reverse order of declaration (last in, first out)
* Defer Example
.play code/defer/defer.go
* Common Defer Idioms
- Put cleanup right after initialization but `defer` it
.play code/defer/defer2.go /^func main/,/^}/
* Exercise 4
- `cd`$intro-to-go-class-exercises/4-first-class-functions/user`
- Open `user.go` in your editor of choice
- Read the instructions
* More Statements
* Loops Again
- We've seen `for` loops with `range`
- Go also supports C-style for loops:
for i := 0; i < 10; i++ {
someFunc(i)
}
- There are no while loops, but `for` loops serve the same purpose:
for a < b {
a *= 2
}
- For loops keep iterating while their condition is true
for { ... } // infinite loop
* Loop Controls
- Can exit a loop with `break`:
for a < b {
if a == 42 {
break
}
}
- Can go to the next iteration with `continue`:
for _, row := range rows {
for i, cell := range row {
if i >= 2 {
continue
}
}
}
* Loop Labels
- Both `break` and `continue` can work with labels:
OuterLoop:
for _, row := range rows {
for i, cell := range row {
if cell == 42 {
break OuterLoop
}
if i >= 2 {
continue OuterLoop
}
}
}
* Switch Statements
- Shorthand for `if` ... `else if` ... `else if` ... `else`
.play code/switch/switch.go
* Switch Statements
- Can use expressions for each `case` if we omit the variable after `switch`:
.play code/switch/switch2.go
* Error Handling
* Go Style Error Handling
- Public interfaces return errors
- Go does have exceptions (`panic()`), but throwing them is considered bad form
- You can throw and catch them in your own package, but they should never affect callers
- It's ok to `panic()` if your package cannot complete initialization
- Can also use `panic()` to exit a goroutine without affecting the main thread (if you catch the panic in the main thread)
* More Reading on Errors
.link https://go.dev/doc/effective_go#errors Effective Go on errors
.link https://blog.golang.org/error-handling-and-go Error handling and Go
.link https://blog.golang.org/defer-panic-and-recover Defer, Panic, and Recover
.link https://blog.golang.org/errors-are-values Errors are values
.link https://pkg.go.dev/github.com/juju/errors?tab=doc Package for wrapping errors
* The Error Type
- Go's built-in error type is called `error`
- This is actually an *interface*, which we'll cover later
- You can create a new `error` with `errors.New("message`goes`here")`
- Go errors are usually returned as the last return value:
func Foo() (bool, string, error) { ... }
* Errors in Action
.play code/errors/errors.go
* Errors in Action
.play code/errors/errors2.go
* Using fmt.Errorf
- If you want to create better string, errors, use `fmt.Errorf()`:
.code code/errors/errorf.go
* Advanced Errors
- We can also create errors as structs:
.code code/errors/error-struct.go /start-of-code/,/end-of-code/
* Exercise 5
- `cd`$intro-to-go-class-exercises/5-error-return/user`
- Open `user.go` in your editor of choice
- Read the instructions
* Unit Testing with "go test"
* Test Files
- When you run `go`test` go tests all the specified packages
- Run `go`test`-v` for more details on failures
- Run it in a directory and it tests whatever is in that directory
- Tests are in files named "foo_test.go", "bar_test.go"
- Test files mostly correspond to the files implementing a package:
user/
├── cache.go
├── cache_test.go
├── db.go
├── db_test.go
├── shared_test.go
├── user.go
└── user_test.go
* Test Functions
- Test functions are in the same package as the code they test
- Have access to private struct members and functions
- Go looks for functions named `TestX`, `TestY`, etc.
- These functions receive a `*testing.T` struct pointer as their sole argument
- All test code must import the `testing` package
* Example Tests
.code code/unit-tests/user_test.go
* The assert Library
.link https://pkg.go.dev/github.com/stretchr/testify/assert?tab=doc
- I'm a big fan of using assertions
- Makes testing a lot nicer
* assert Example
.code code/unit-tests/user_assert_test.go
* Exercise 6
- `cd`$intro-to-go-class-exercises/6-unit-tests/calc`
- Open `calc_test.go` in your editor of choice
- Read the instructions
* Types, Interfaces, and OO in Go
* A Go Method
- In Go, methods are associated with types
- Any type - struct types, pointers, strings, etc.
- Method names cannot overlap with struct field names
- Methods are called as `value.method(...)`
* Method Example
.play code/oo/methods.go
* How Methods Work
func (m mystring) foo(arg int) bool {
...
}
- Simply defining a func with a receiver makes it a method
- The receiver is the thing the method is called on
- Comes before the method name
- Types and their methods must all be declared in the same package
* Methods and Pointers
- Methods with pointer receiver automatically take references:
type mystring string
func (m *mystring) method() { ... }
var m mystring = "text"
m.method()
- Calling `method()` will take a reference to `m` and pass that to `method()`
* Constructors
- Go has no special constructor syntax
- Typical packages provide a single `New()` function and/or several `NewX()` functions
- For example, `user.New()`, `user.NewCache()`, `user.NewGroup()`
- Constructors are expected to return a new value of the relevant type (or a pointer)
* Accessors and Attributes
- Go has no special accessor or attribute syntax
- You can provide accessors to a type's data by writing the appropriate methods
* Accessors Example
.play code/oo/accessors.go
* Accessors Gotcha
- Set methods must take a reference because values are passed by copy
// BAD CODE - WILL NOT WORK
func (d Document) SetTitle(title string) { d.title = title }
- `d` is a copy of the `Document` struct so the title is set on a struct that is then thrown away
* Accessor Naming
- Go style is to use `Value()` for get methods and `SetValue()` for set methods
- But avoid setters because mutable state is the devil
- But OO design is a topic for another class entirely
- But seriously, avoid setters whenever possible
* Exercise 7
- `cd`$intro-to-go-class-exercises/7-basic-oo/user`
- Open `user.go` in your editor of choice
- Read the instructions
* Struct Composition
- Sort of vaguely like inheritance
- Can embed a struct in another struct
- Methods on embedded struct can be called on container struct
* Struct Composition
.play code/oo/composition.go /START1 OMIT/,/END1 OMIT/
* Struct Composition
.play code/oo/composition.go /START2 OMIT/,/END2 OMIT/
* Interfaces
- An interface is a list of methods *without implementations*
- Go has many interface types defined in the core library
- You can define your own interfaces
- You can also require receivers that conform to an interface in your functions
- Any receiver which implements these methods conforms to the interface
* Interface Example
.play code/oo/interfaces.go
* Some Common Built-in Interfaces
- `io.Reader`
type Reader interface {
Read(p []byte) (n int, err error)
}
- `io.Writer`
type Writer interface {
Write(p []byte) (n int, err error)
}
- `Error`
type error interface {
Error() string
}
* Interfaces Of Interfaces
- An interface can include other interfaces:
type ReadWriter interface {
Reader
Writer
}
- A `ReadWriter` must implement all the methods from `Reader` and `Writer`
- And an interface can specify an interface which specifies other interfaces:
type File interface {
ReadWriter
Close() error
}
* Requiring an Interface
- Interfaces can be used like any other type in a function:
func (var SomeInterface) { ... }
- Also used in type assertions, which we will cover soon
* Exercise 8
- `cd`$intro-to-go-class-exercises/8-interfaces/user`
- Open `user.go` in your editor of choice
- Read the instructions
* Satisfying an Interface
- You can write code that satisfies any interface, including built-ins