-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbasic.slide
More file actions
610 lines (414 loc) · 18.8 KB
/
Copy pathbasic.slide
File metadata and controls
610 lines (414 loc) · 18.8 KB
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
The Go Programming Language
Basic
Tags: go, golang
Anuchit Prasertsang
Developer
anuchit.prasertsang@gmail.com
https://github.com/AnuchitO
@twitter_AnuchitO
* Basic
* Installing
.link https://golang.org/dl/ Download https://golang.org/dl
*mac/linux*
Download file.tar.gz
~/go1.x.x
*windows*
Download file.zip
C:\go1.x.x
* GOROOT
*mac/linux*
export GOROOT=~/go1.x.x
export GOBIN=$GOPATH/bin
export PATH=$GOBIN:$GOROOT/bin:$PATH
*windows*
set GOROOT=C:\go1.x.x
set GOBIN=%GOPATH%\bin
set PATH=%GOBIN%;%GOROOT%\bin;%PATH%
* GOROOT vs GOPATH
*GOROOT* is a root of your Go installation.
If you are a Java user, $GOROOT is similar in effect to $JAVA_HOME
*GOPATH* is a environment variable specifies the location of your workspace.
It defaults to a directory named go inside your home directory
- Unix
$HOME/go
- Windows
%USERPROFILE%\go (usually C:\Users\YourName\go)
* Project structure
bin/
hello # command executable
outyet # command executable
pkg/
linux_amd64/
github.com/golang/example/
stringutil.a # package object
src/
github.com/golang/example/
.git/ # Git repository metadata
hello/
hello.go # command source
outyet/
main.go # command source
main_test.go # test source
stringutil/
reverse.go # package source
reverse_test.go # test source
golang.org/x/image/
.git/ # Git repository metadata
bmp/
reader.go # package source
writer.go # package source
... (many more repositories and packages omitted) ...
* editor
.image editor.png
* os
.image dev_on_os.png
* Keywords
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
* Packages
- Every Go program is made up of packages.
- Programs start running in package main.
.play basic/packages.go
- By convention, the package name is the same as the last element of the import path. For instance, the *"math/rand"* package comprises files that begin with the statement package *rand*.
* Imports
- This code groups the imports into a parenthesized, "factored" import statement.
.code basic/imports.go
- You can also write multiple import statements, like:
import "fmt"
import "math"
But it is good style to use the factored import statement.
* Exported names
- In Go, a name is exported if it begins with a *capital* *letter*.
Pizza
Pi
Println
: pizza and pi do not start with a capital letter, so they are not exported.
- When importing a package *math.Pi*
- Any "unexported" names are not accessible from outside the package.
: workshop => refactor function to package
* Variables
- The *var* statement declares a list of variables; as in function argument lists, the type is last.
- A *var* statement can be at package or function level. We see both in this example.
.play basic/variables.go
* Variables with initializers
- If an initializer is present, the type can be omitted; the variable will take the type of the initializer.
.play basic/variables_with_initializers.go
* Short variable declarations
- Inside a function, the *:=* short assignment statement can be used in place of a *var* declaration with implicit type.
.play basic/sort_variable_initialinze.go
- Outside a function, every statement begins with a keyword (_var_, _func_, and so on) and so the _:=_ construct is not available.
* Basic types
Go's basic types are
bool
string
int int8 int16 int32 int64
uint uint8 uint16 uint32 uint64 uintptr
byte // alias for uint8
rune // alias for int32
// represents a Unicode code point
float32 float64
complex64 complex128
The _int_, _uint_, and _uintptr_ types are usually 32 bits wide on 32-bit systems and 64 bits wide on 64-bit systems.
When you need an integer value you should use _int_ unless you have a specific reason to use a sized or unsigned integer type.
* Zero values
Variables declared without an explicit initial value are given their zero value.
The zero value is:
*0* for numeric types,
*false* for the boolean type
*""* (the empty string) for strings.
.play basic/zero.go
%q a double-quoted string safely escaped with Go syntax
* Type conversions
The expression *T(v)* converts the value *v* to the type *T*.
Some numeric conversions:
var i int = 42
var f float64 = float64(i)
var u uint = uint(f)
Or, put more simply:
i := 42
f := float64(i)
u := uint(f)
Unlike in C, in Go assignment between items of different type requires an explicit conversion.
* Type conversions - example
Try removing the _float64_ or _uint_ conversions in the example and see what happens.
.code basic/type_conversions.go
* Type inference
When declaring a variable without specifying an explicit type
(either by using the *:=* syntax or *var* *=* expression syntax),
the variable's type is inferred from the value on the right hand side.
When the right hand side of the declaration is typed, the new variable is of that same type:
var i int
j := i // j is an int
But when the right hand side contains an untyped numeric constant,
the new variable may be an _int_, _float64_, or _complex128_ depending on the precision of the constant:
i := 42 // int
f := 3.142 // float64
g := 0.867 + 0.5i // complex128
* Type inference - example
Try changing the initial value of _v_ in the example code and observe how its type is affected.
.code basic/type_inference.go
* Constants
Constants are declared like variables, but with the const keyword.
Constants can be _character_, _string_, _boolean_, or _numeric_ values.
Constants *cannot* be declared using the := syntax.
.play basic/constants.go
: * Numeric Constants
: Numeric constants are high-precision values.
: An untyped constant takes the type needed by its context.
: Try printing needInt(Big) too.
: (An int can store at maximum a 64-bit integer, and sometimes less.)
: .play basic/numeric_constants.go /START/,/END/
* Constants - iota
iota expression is repeated by the other constants
until another assignment or type declaration shows up.
* Functions
- A function can take zero or more arguments.
- In this example, *add* takes two parameters of type *int*.
- Notice that the _type_ comes _after_ the _variable_ _name_.
.code basic/functions.go
func add(x, y int) int
: (For more about why types look the way they do, see the article on Go's declaration syntax.)
* Multiple results
- a function can return any number of results
- the *swap* function returns two string.
.play basic/multiple_results.go /START/,/END/
* Named return values
- Go's return values may be named. If so, they are treated as variables defined at the top of the function.
.code basic/named_results.go /START/,/END/
- A return statement without arguments returns the named return values. This is known as a *"naked"* return.
- Naked return statements should be used only in short functions.
: They can harm readability in longer functions.
: These names should be used to document the meaning of the return values.
* Function values
*Functions* *are* *values* too. They can be *passed* *around* just like other values.
Function values may be used as function arguments and return values.
.code moretypes/functions_values.go
* Function closures
.code moretypes/functions_closures.go
* Exercise: Fibonacci closure
Implement a _fibonacci_ function that returns a function (a closure) that returns successive fibonacci numbers
F0, the "0" is omitted (0, 1, 1, 2, 3, 5, ...)
.code moretypes/exercise_functions_i.go
* Flow Control
* For
Go has only one looping construct, the *for* loop.
.play flowcontrol/for.go /START/,/END/
The basic *for* loop has three components separated by semicolons:
the init statement: executed before the first iteration
the condition expression: evaluated before every iteration
the post statement: executed at the end of every iteration
The init statement will often be a short variable declaration,
and the variables declared there are visible only in the scope of the *for* statement.
The loop will stop iterating once the boolean condition evaluates to *false*.
Note: there are no parentheses surrounding
* For continued
The init and post statements are optional.
.play flowcontrol/for_continued.go /START/,/END/
* For is Go's "while"
At that point you can drop the semicolons: C's while is spelled for in Go.
.play flowcontrol/for_is_gos_while.go /START/,/END/
* Forever
If you omit the loop condition it loops forever, so an infinite loop is compactly expressed.
.play flowcontrol/forever.go /START/,/END/
* If
Go's *if* statements are like its _for_ loops;the expression need not be surrounded
by parentheses ( ) but the braces *{* *}* are *required*.
.play flowcontrol/if.go /START/,/END/
* If with a short statement
Like _for_, the *if* statement can start with a short statement to execute before the condition.
Variables declared by the statement are only in scope until the end of the _if_.
(Try using _v_ in the last _return_ statement.)
.code flowcontrol/if_with_a_short_statement.go /START/,/END/
* If and else
Variables declared inside an *if* short statement are also available inside any of the *else* blocks.
.code flowcontrol/if_and_else.go /START/,/END/
* Exercise: Loops and Functions
* Switch
A *switch* statement is a shorter way to write a sequence of _if_ _-_ _else_ statements.
It runs the first case whose value is equal to the condition expression.
.play flowcontrol/switch.go /START/,/END/
Go *only* *runs* *the* *selected* *case*, not all the cases that follow.
the *break* statement is provided automatically in Go.
: Go's switch is like the one in C, C++, Java, JavaScript, and PHP,
: Another important difference is that Go's switch cases need not be constants, and the values involved need not be integers.
* Switch evaluation order
Switch cases evaluate cases from top to bottom, stopping when a case succeeds.
(For example,
switch i {
case 0:
case f():
}
does not call _f_ *if* *i==0* .)
.play flowcontrol/switch_evaluation_order.go /START/,/END/
* Switch with no condition
Switch without a condition is the same as *switch* *true*.
.play flowcontrol/switch_with_no_condition.go
This construct can be a clean way to write long if-then-else chains.
* Defer
A defer statement defers the execution of a function until the surrounding function returns.
.play flowcontrol/defer.go
The deferred call's arguments are evaluated immediately,
but the function call is not executed until the surrounding function returns.
* Stacking defers
Deferred function calls are pushed onto a stack. When a function returns, its deferred calls are executed in last-in-first-out order.
.play flowcontrol/defer_stacking.go
: To learn more about defer statements read this https://blog.golang.org/defer-panic-and-recover.
* More types
* Pointers
Go has pointers. A pointer holds the memory address of a value.
The type ****T* is a pointer to a *T* value. Its zero value is *nil*.
var p *int
The *&* operator generates a pointer to its operand.
i := 42
p = &i
The *** operator denotes the pointer's underlying value.
fmt.Println(*p) // read i through the pointer p
*p = 21 // set i through the pointer p
This is known as "dereferencing" or "indirecting".
Unlike C, Go has no pointer arithmetic.
* Pointers - example
.code moretypes/pointers.go
* Structs
A _struct_ is a collection of fields.
.play moretypes/structs.go
* Struct Fields
Struct fields are accessed using a dot.
.play moretypes/structs_fields.go
* Pointers to structs
Struct fields can be accessed through a struct pointer.
.play moretypes/structs_pointers.go /START/,/END/
To access the field *X* of a struct when we have the struct pointer *p*
we could write *(***p).X*. However, that notation is cumbersome,
so the language permits us instead to write just *p.X*,
without the explicit dereference.
* Struct Literals
A struct literal denotes a newly allocated struct value by listing the values of its fields.
You can list just a subset of fields by using the *Name:* syntax. (And the order of named fields is irrelevant.)
.play moretypes/structs_literals.go /START/,/END/
The special prefix *&* returns a pointer to the struct value.
* Arrays
The type *[n]T* is an array of *n* values of type *T*.
The expression
var a [10]int
declares a variable a as an array of ten integers.
.play moretypes/array.go /START/,/END/
An array's length is part of its type, so arrays _cannot_ be _resized_.
This seems limiting, but don't worry; Go provides a convenient way of working with arrays.
* Slices
An array has a fixed size. A slice, on the other hand, is a dynamically-sized, flexible view into the elements of an array. In practice, slices are much more common than arrays.
The type *[]T* is a slice with elements of type *T*.
A slice is formed by specifying two indices, a low and high bound, separated by a colon:
a[low : high]
This selects a *half-open* *range* which _includes_ the _first_ element, but _excludes_ the _last_ one.
The following expression creates a slice which includes elements 1 through 3 of *a*:
a[1:4]
* Slices - example, create slices from array
.play moretypes/slices.go /START/,/END/
* Slices are like references to arrays
A slice does not store any data, it just describes a section of an underlying array.
.play moretypes/slices_pointers.go /START/,/END/
Changing the elements of a slice modifies the corresponding elements of its underlying array.
Other slices that share the same underlying array will see those changes.
* Slice literals
A slice literal is like an array literal without the length.
[]bool{true, true, false}
the array will be create, then builds a slice that references it:
.play moretypes/slices_literals.go /START/,/END/
* Slice bound defaults
When slicing, you may omit the high or low bounds to use their defaults instead.
For the array
var a [10]int
these slice expressions are equivalent:
a[0:10]
a[:10]
a[0:]
a[:]
The default is _zero_ for the low bound and the _length_ of the slice for the high bound.
* Slice bound defaults - example
.play moretypes/slices_bounds.go
* Slice length and capacity
A slice has both a _length_ and a _capacity_.
The length of a slice is the number of elements it contains.
The capacity of a slice is the number of elements in the underlying array, counting from the first element in the slice.
The length and capacity of a slice *s* can be obtained using the expressions *len(s)* and *cap(s)*.
* Slice length and capacity - example
You can extend a slice's length by re-slicing it, provided it has sufficient capacity. Try changing one of the slice operations in the example program to extend it beyond its capacity and see what happens.
.code moretypes/slices_len_cap.go /START/,/END/
* Nil slices
The zero value of a slice is *nil*.
A nil slice has a length and capacity of 0 and has no underlying array.
.play moretypes/slices_nil.go
* Creating a slice with make
Slices can be created with the built-in *make* function; this is how you create dynamically-sized arrays.
The *make* function allocates a zeroed array and returns a slice that refers to that array:
a := make([]int, 5) // len(a)=5
To specify a capacity, pass a third argument to make:
b := make([]int, 0, 5) // len(b)=0, cap(b)=5
b = b[:cap(b)] // len(b)=5, cap(b)=5
b = b[1:] // len(b)=4, cap(b)=4
* Creating a slice with make - example
.play moretypes/slices_make.go /START/,/END/
* Slices of slices
Slices can contain any type, including other slices.
.play moretypes/slices_of_slices.go /START/,/END/
* Appending to a slice
It is common to *append* new elements to a slice, and so Go provides a built-in append function.
.link https://golang.org/pkg/builtin/#append append documents
func append(s []T, vs ...T) []T
The first parameter *s* of *append* is a slice of type *T*, and the rest are *T* values to append to the slice.
The resulting value of *append* is a slice containing all the elements of the original slice plus the provided values.
If the backing array of *s* is too small to fit all the given values a bigger array will be allocated. The returned slice will point to the newly allocated array.
.link https://blog.golang.org/go-slices-usage-and-internals slices usages and internals
* Appending to a slice - example
.play moretypes/append.go
* Range
The range form of the for loop iterates over a slice or map.
When ranging over a slice, two values are returned for each iteration. The *first* is the *index*, and the *second* is a *copy* *of* the *element* at that index.
.play moretypes/range.go /START/,/END/
* Range continued
You can skip the index or value by assigning to *_*.
If you only want the index, drop the *,* *value* entirely.
.play moretypes/range_continue.go /START/,/END/
* Exercise: Slices
Implement *Pic*. It should return a slice of length *dy*, each element of which is a slice of *dx* 8-bit unsigned integers. When you run the program, it will display your picture, interpreting the integers as grayscale (well, bluescale) values.
The choice of image is up to you. Interesting functions include _(x+y)/2_, _x*y_, and _x^y_.
(You need to use a loop to allocate each *[]uint8* inside the *[][]uint8*.)
(Use *uint8(intValue)* to convert between types.)
.code moretypes/exercise_slices.go
* Exercise: Slices - example answer
.play moretypes/exercise_slices_answer.go
* Maps
A map maps keys to values.
The zero value of a map is *nil*. A *nil* map has no keys, nor can keys be added.
The make function returns a *map* of the given type, initialized and ready for use.
.play moretypes/maps.go /START/,/END/
* Exercise: Maps I
- create map
key - student id
value - student information, name, class, age, no
* Map literals
Map literals are like struct literals, but the keys are required.
.play moretypes/map_literals.go /START/,/END/
* Map literals continued
If the top-level type is just a type name, you can omit it from the elements of the literal.
.play moretypes/map_literals_continue.go /START/,/END/
* Mutating Maps
Insert or update an element in map m:
m[key] = elem
Retrieve an element:
elem = m[key]
Delete an element:
delete(m, key)
Test that a key is present with a two-value assignment:
elem, ok = m[key]
If key is in m, ok is true. If not, ok is false.
If key is not in the map, then elem is the zero value for the map's element type.
* Mutating Maps - example
.play moretypes/maps_mutate.go /START/,/END/
* Exercise: Maps II
Implement *WordCount*. It should return a map of the counts of each “word” in the string *s*.
.code moretypes/maps_exercise_II.go
You might find *strings.Fields* helpful.