-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathGO General Notes.txt
743 lines (610 loc) · 13.1 KB
/
GO General Notes.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
## https://golang.org/pkg/builtin
# Using gitlab personal access token
git config --global credential.helper store
echo "https://oauth2:XXXXXXXXXX@git.cafebazaar.ir" >> ~/.git-credentials
# install go
cd ~/Downloads
export GOLANG_VERSION="1.14.4"
curl "https://dl.google.com/go/go${GOLANG_VERSION}.linux-amd64.tar.gz" -o golang.tar.gz
tar -C ~/.local -xzf golang.tar.gz
rm -f golang.tar.gz
sudo vim /etc/environment
....................................
PATH+="/usr/local/go/bin"
....................................
vim ~/.profile
....................................
export GOPATH=$HOME/go
export GOROOT=$HOME/.local/go
export GOBIN=$GOPATH/bin
export PATH=$PATH:$GOROOT/bin:$GOBIN
....................................
# reboot
sudo reboot
# check go version
go version
# install dep
curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh
# source file locations
~/go/src/<PACKAGE>
# hello world app
....................................
package main
import "fmt"
func main() {
fmt.Printf("hello, world\n")
}
....................................
# build helloworld app
cd ~/go/src/helloworld
go build
./helloworld
##############################################
int: int64 on 64bit systems
float32, float64
rune -> int32
%T prints type
%g, %G good for floating points (scientific for large values)
%v the value in a default format when printing structs, the plus flag (%+v) adds field names
%q a single-quoted character literal safely escaped with Go syntax.
import "fmt"
import "math/rand"
->
import (
"fmt"
"math/rand"
)
func add(x int, y int) int {
return x + y
}
func add(x, y int) int {
return x + y
}
func swap(x, y string) (string, string) {
return y, x
}
a, b := swap("hello", "world")
# named return value
# naked return
# good for short functions because it hurts readability
func split(sum int) (x, y int) {
x = sum * 4 / 9
y = sum - x
return
}
# variable declaration
# we have global declarations
# Variables declared without an explicit initial value are given their zero value.
# 0 for numeric types,
# false for the boolean type, and
# "" (the empty string) for strings.
var x int
var x, y int
var i, j int = 1, 2
var (
i int
j string
)
# type conversion
i := 42
f := float64(i)
# constants
# Constants cannot be declared using the := syntax.
# Numeric constants are high-precision values.
# An untyped constant takes the type needed by its context.
const Pi = 3.14
for i := 0; i < 10; i++ {
sum += i
}
# For is Go's "while"
for sum < 1000 {
sum += sum
}
# Forever
for {
}
# If with a short statement
if v := math.Pow(x, n); v < lim {
return v
}
# switch
# -> IT DOES NOT NEED TO BE CONSTANTS
# -> NO BREAK
# -> COULD BE STRING OR ANYTHING!
import (
"fmt"
"runtime"
)
switch os := runtime.GOOS; os {
case "darwin":
fmt.Println("OS X.")
case "linux":
fmt.Println("Linux.")
default:
// freebsd, openbsd,
// plan9, windows...
fmt.Printf("%s.", os)
}
# Switch with no condition
# This construct can be a clean way to write long if-then-else chains.
switch {
case t.Hour() < 12:
fmt.Println("Good morning!")
case t.Hour() < 17:
fmt.Println("Good afternoon.")
default:
fmt.Println("Good evening.")
}
# defer
# Stacking defers
defer fmt.Println("world")
fmt.Println("hello")
# pointers
# Unlike C, Go has no pointer arithmetic.
var p *int
p := &i
*p = *p / 37
# struct
type Vertex struct {
X int
Y int
}
Vertex{1, 2}
v1 = Vertex{1, 2} // has type Vertex
v2 = Vertex{X: 1} // Y:0 is implicit
v3 = Vertex{} // X:0 and Y:0
p = &Vertex{1, 2} // has type *Vertex
# pointer to struct
p := &v
p.X = 1e9
# arrays
# SHOULD HAVE CONSTANT BOUNDARY
var a [10]int
primes := [6]int{2, 3, 5, 7, 11, 13}
# array slice
# A slice does not store any data, it just describes a section of an underlying array.
a[low : high]
# slice defaults
a[0:10]
a[:10]
a[0:]
a[:]
# A slice literal is like an array literal without the length.
[]int{2, 3, 5, 7, 11, 13}
func printSlice(s []int) {
fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
}
s := []struct {
i int
b bool
}{
{2, true},
{3, false},
{5, true},
{7, true},
{11, false},
{13, true},
}
# nil slice
# The zero value of a slice is nil.
# A nil slice has a length and capacity of 0 and has no underlying array.
if s == nil {
fmt.Println("nil!")
}
# creating slices with 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
# Appending to a slice
s = append(s, 2, 3, 4)
# range
var pow = []int{1, 2, 4, 8, 16, 32, 64, 128}
func main() {
for i, v := range pow {
fmt.Printf("2**%d = %d\n", i, v)
}
}
# range skipping
func main() {
pow := make([]int, 10)
for i := range pow {
pow[i] = 1 << uint(i) // == 2**i
}
for _, value := range pow {
fmt.Printf("%d\n", value)
}
}
# maps
m = make(map[string]Vertex)
m["Bell Labs"] = Vertex{
40.68433, -74.39967,
}
var m map[string]Vertex
# map literals
var m = map[string]Vertex{
"Bell Labs": Vertex{
40.68433, -74.39967,
},
"Google": Vertex{
37.42202, -122.08408,
},
}
# ONLY FOR STRUCTS
var m = map[string]Vertex{
"Bell Labs": {40.68433, -74.39967},
"Google": {37.42202, -122.08408},
}
# delete element
delete(m, key)
# test element exists
elem, ok = m[key]
# function values
func compute(fn func(float64, float64) float64) float64 {
return fn(3, 4)
}
hypot := func(x, y float64) float64 {
return math.Sqrt(x*x + y*y)
}
# methods
type Vertex struct {
X, Y float64
}
func (v Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
# pointer receivers
# Since methods often need to modify their receiver, pointer receivers are more common than value receivers.
# The second is to avoid copying the value on each method call. This can be more efficient if the receiver is a large struct, for example.
# In general, all methods on a given type should have either value or pointer receivers, but not a mixture of both.
func (v *Vertex) Scale(f float64) {
v.X = v.X * f
v.Y = v.Y * f
}
# interfaces
# interface implementation is implicit
type APerson interface {
getName() string
}
type Person struct {
name string
}
## OPTION1: USING VALUE RECEIVER
func (p *Person) getName() string {
return p.name
}
var p APerson
p = &Person{name: "mehdi"}
## OPTION2: USING POINTER RECEIVER
func (p Person) getName() string {
return p.name
}
var p APerson
p = Person{name: "mehdi"}
# Under the covers, interface values can be thought of as a tuple of a value and a concrete type:
# (value, type)
# In some languages this would trigger a null pointer exception, but in Go it is common to write methods that gracefully handle being called with a nil receiver (as with the method M in this example.)
-> SO (nil, type) CAN BE HANDLED USING INTERFACES
-> BUT STILL (nil, nil) IS RUNTIME EXCEPTION
# empty interface
interface{}
# An empty interface may hold values of any type. (Every type implements at least zero methods.)
# Empty interfaces are used by code that handles values of unknown type. For example, fmt.Print takes any number of arguments of type interface{}.
# type assertion
# triggers PANIC
t := i.(T)
# type testing
# DOES NOT TRIGGER PANIC
t, ok := i.(T)
# type switch
func do(i interface{}) {
switch v := i.(type) {
case int:
fmt.Printf("Twice %v is %v\n", v, v*2)
case string:
fmt.Printf("%q is %v bytes long\n", v, len(v))
default:
fmt.Printf("I don't know about type %T!\n", v)
}
}
# Stringer interface
type Stringer interface {
String() string
}
# working with times (basic)
imprort "time"
var t time.Time
t := time.Now()
# errors
type error interface {
Error() string
}
func run() error {
...
}
# error example
i, err := strconv.Atoi("42")
if err != nil {
fmt.Printf("couldn't convert number: %v\n", err)
return
}
fmt.Println("Converted integer:", i)
# Reader interface
func (T) Read(b []byte) (n int, err error)
# reader example
func main() {
r := strings.NewReader("Hello, Reader!")
b := make([]byte, 8)
for {
n, err := r.Read(b)
fmt.Printf("n = %v err = %v b = %v\n", n, err, b)
fmt.Printf("b[:n] = %q\n", b[:n])
if err == io.EOF {
break
}
}
}
# image package
package image
type Image interface {
ColorModel() color.Model
Bounds() Rectangle
At(x, y int) color.Color
}
# sleep in ms
time.Sleep(100 * time.Millisecond)
# goroutine
go f(x, y, z)
# make channel
ch := make(chan int)
# send and receive data
c <- sum // send sum to c
x, y := <-c, <-c // receive from c
# buffered channel
ch := make(chan int, 100)
cap(ch)
# close channel by sender
close(c)
# test if channel is still open
v, ok := <-ch
# use range operator on channels which can be closed
c := make(chan int, 10)
go fibonacci(cap(c), c)
for i := range c {
fmt.Println(i)
}
func fibonacci(n int, c chan int) {
x, y := 0, 1
for i := 0; i < n; i++ {
c <- x
x, y = y, x+y
}
close(c)
}
# select operator
func fibonacci(c, quit chan int) {
x, y := 0, 1
for {
select {
case c <- x:
x, y = y, x+y
case <-quit:
fmt.Println("quit")
return
default:
fmt.Println("wtf!")
}
}
}
# mutex
mux = sync.Mutex{}
mux.Lock()
defer mux.Unlock()
# new for structs
# will return *TYPE
type Ball struct {hits int}
b := new(Ball)
# cause panic
panic("message")
# timeout
time.AfterFunc(3 * time.Second, func() {
})
# function that returns a receive only channel
func() <-chan int {
}
# golang race detector
go run -race myProg.go
# channel of channels can be used for RPC to goroutines
func incLoop(val chan chan int) {
for {
v := <-val
v<- (<-v) + 1
}
}
func main() {
ch := make(chan chan int)
go incLoop(ch)
ch2 := make(chan int)
ch<- ch2
ch2 <- 5
fmt.Println(<-ch2)
}
# nil channels always block!
# can be used together with select statements
for {
var first Item
var updates chan Item
if len(pending) > 0 {
first = s.updates[0]
updates = s.updates
}
select {
case updates <- first:
pending = pending[1:]
}
}
# timeout with channels, good for
# using with select statement
# and also prevents leaks!
startFetch := time.After(fetchDelay)
select {
case <-startFetch:
}
# concatting arrays
a := []int{1, 2, 3}
b := []int{4, 5, 6}
a = append(a, b...)
for _, v := range a {
fmt.Println(v)
}
# composition
type A struct {
a, b int
}
type B struct {
A
c int
}
# string literal for holding " ' etc.
# using grave character
str := `{"a":b}`
# remember duration type
time.Duration
# function taking infinite arguments
func sum(args ...int) (result int) {
fmt.Println(len(args))
for _, v := range args {
result += v
}
return
}
### Using condition variable
m := sync.Mutex{}
cond := sync.NewCond(&m)
func() {
cond.L.Lock()
defer cond.L.Unlock()
cond.Signal()
}()
func() {
cond.L.Lock()
defer cond.L.Unlock()
cond.Wait()
}()
## REMEMBER: PRODUCERS SHOULD ALWAYS CLOSE THEIR OUTPUT CHANNELS!
## BEGIN EXAMPLE PRODUCER ##
type producer struct {
ch chan int
}
func NewProducer() *producer {
return &producer{
ch: make(chan int),
}
}
func (p *producer) start(d time.Duration) <-chan int {
go func() {
next := 0
ch := p.ch
var sleep <-chan time.Time
for {
select {
case ch <- next:
next++
ch = nil
sleep = time.After(d)
case <-sleep:
ch = p.ch
case v := <-p.ch:
if v == -1 {
close(p.ch)
return
}
}
}
}()
return p.ch
}
func (p *producer) close() {
p.ch <- -1
}
## END EXAMPLE PRODUCER ##
## BEGIN MERGER ##
func merge(chs ...<-chan int) <-chan int {
wg := sync.WaitGroup{}
result := make(chan int)
read := func (ch <-chan int) {
for x := range ch {
result <- x
}
wg.Done()
}
wg.Add(len(chs))
for _, ch := range chs {
go read(ch)
}
go func() {
wg.Wait()
close(result)
}()
return result
}
## END MERGER ##
## IMPORTANT NOTE!
## IMPORTANT NOTE!
channels when closed, they do not get closed immediately,
but after their data was read successfuly, so all data
can be consumed safely while channel was marked to be closed
## IMPORTANT NOTE!
## IMPORTANT NOTE!
## Worker Example
func worker(n int, ch <-chan int, wg *sync.WaitGroup) {
defer wg.Done()
c := ch
var sleep <-chan time.Time
for {
select {
case v, t := <-c:
if t {
fmt.Println("worker", n, v)
c = nil
sleep = time.After(time.Duration(rand.Intn(200) + 100) * time.Millisecond)
} else {
return
}
case <-sleep:
c = ch
}
}
}
## unit testing
1. name file xxx_test.go, e.g. sum.go and sum_test.go
2. import "testing"
3. unit tests start with Test e.g. func TestSum
4. unit tests take 1 parameter of type *testing.T e.g.
func TestSum(t *testing.T) {
5. use t.Error, t.Errorf, t.Log, t.Logf, t.Fail
6. Use table testing pattern
tables := []struct {x, y, sum int}{
{1,2, 3},
{5, 6, 11},
}
for _, table := range tables {
actual := Sum(table.x, table.y)
if table.sum != actual {
t.Errorf("Sum(%v,%v) expected %v actual %v\n", table.x, table.y, table.sum, actual)
}
}
7. run tests "go test"
8. coverage with "go test -cover"
go test -cover -coverprofile=c.out
go tool cover -html=c.out -o coverage.html
## godoc providing examples
## provide examples in file xxx_test.go
## Example<Type>
## Example<Type>_<Label>
## e.g. for below in doc.go
## type Examples int
# file: doc_test.go
func ExampleExamples() {
func ExampleExamples_other() {
# start godoc in server mode,
godoc -html -index -http :6060