OSDN Git Service

Regular updates
[twpd/master.git] / go.md
1 ---
2 title: Go
3 layout: 2017/sheet
4 prism_languages: [go, bash]
5 weight: -3
6 tags: [Featured]
7 category: C-like
8 updated: 2020-06-21
9 ---
10
11 ## Getting started
12 {: .-three-column}
13
14 ### Introduction
15 {: .-intro}
16
17 - [A tour of Go](https://tour.golang.org/welcome/1) _(tour.golang.org)_
18 - [Go repl](https://repl.it/languages/go) _(repl.it)_
19 - [Golang wiki](https://github.com/golang/go/wiki/) _(github.com)_
20
21 ### Hello world
22 {: .-prime}
23
24 #### hello.go
25 {: .-file}
26
27 ```go
28 package main
29
30 import "fmt"
31
32 func main() {
33   message := greetMe("world")
34   fmt.Println(message)
35 }
36
37 func greetMe(name string) string {
38   return "Hello, " + name + "!"
39 }
40 ```
41
42 ```bash
43 $ go build
44 ```
45
46 Or try it out in the [Go repl](https://repl.it/languages/go), or [A Tour of Go](https://tour.golang.org/welcome/1).
47
48 ### Variables
49
50 #### Variable declaration
51
52 ```go
53 var msg string
54 msg = "Hello"
55 ```
56
57 #### Shortcut of above (Infers type)
58
59 ```go
60 msg := "Hello"
61 ```
62
63 ### Constants
64
65 ```go
66 const Phi = 1.618
67 ```
68
69 Constants can be character, string, boolean, or numeric values.
70
71 See: [Constants](https://tour.golang.org/basics/15)
72
73 ## Basic types
74 {: .-three-column}
75
76 ### Strings
77
78 ```go
79 str := "Hello"
80 ```
81
82 ```go
83 str := `Multiline
84 string`
85 ```
86
87 Strings are of type `string`.
88
89 ### Numbers
90
91 #### Typical types
92
93 ```go
94 num := 3          // int
95 num := 3.         // float64
96 num := 3 + 4i     // complex128
97 num := byte('a')  // byte (alias for uint8)
98 ```
99
100 #### Other types
101
102 ```go
103 var u uint = 7        // uint (unsigned)
104 var p float32 = 22.7  // 32-bit float
105 ```
106
107 ### Arrays
108
109 ```go
110 // var numbers [5]int
111 numbers := [...]int{0, 0, 0, 0, 0}
112 ```
113
114 Arrays have a fixed size.
115
116 ### Slices
117
118 ```go
119 slice := []int{2, 3, 4}
120 ```
121
122 ```go
123 slice := []byte("Hello")
124 ```
125
126 Slices have a dynamic size, unlike arrays.
127
128 ### Pointers
129
130 ```go
131 func main () {
132   b := *getPointer()
133   fmt.Println("Value is", b)
134 }
135 ```
136 {: data-line="2"}
137
138 ```go
139 func getPointer () (myPointer *int) {
140   a := 234
141   return &a
142 }
143 ```
144 {: data-line="3"}
145
146 ```go
147 a := new(int)
148 *a = 234
149 ```
150 {: data-line="2"}
151
152 Pointers point to a memory location of a variable. Go is fully garbage-collected.
153
154 See: [Pointers](https://tour.golang.org/moretypes/1)
155
156 ### Type conversions
157
158 ```go
159 i := 2
160 f := float64(i)
161 u := uint(i)
162 ```
163
164 See: [Type conversions](https://tour.golang.org/basics/13)
165
166 ## Flow control
167 {: .-three-column}
168
169 ### Conditional
170
171 ```go
172 if day == "sunday" || day == "saturday" {
173   rest()
174 } else if day == "monday" && isTired() {
175   groan()
176 } else {
177   work()
178 }
179 ```
180 {: data-line="1,3,5"}
181
182 See: [If](https://tour.golang.org/flowcontrol/5)
183
184 ### Statements in if
185
186 ```go
187 if _, err := doThing(); err != nil {
188   fmt.Println("Uh oh")
189 }
190 ```
191 {: data-line="1"}
192
193 A condition in an `if` statement can be preceded with a statement before a `;`. Variables declared by the statement are only in scope until the end of the `if`.
194
195 See: [If with a short statement](https://tour.golang.org/flowcontrol/6)
196
197 ### Switch
198
199 ```go
200 switch day {
201   case "sunday":
202     // cases don't "fall through" by default!
203     fallthrough
204
205   case "saturday":
206     rest()
207
208   default:
209     work()
210 }
211 ```
212
213 See: [Switch](https://github.com/golang/go/wiki/Switch)
214
215 ### For loop
216
217 ```go
218 for count := 0; count <= 10; count++ {
219   fmt.Println("My counter is at", count)
220 }
221 ```
222
223 See: [For loops](https://tour.golang.org/flowcontrol/1)
224
225 ### For-Range loop
226
227 ```go
228 entry := []string{"Jack","John","Jones"}
229 for i, val := range entry {
230   fmt.Printf("At position %d, the character %s is present\n", i, val)
231 }
232 ```
233
234 See: [For-Range loops](https://gobyexample.com/range)
235
236 ## Functions
237 {: .-three-column}
238
239 ### Lambdas
240
241 ```go
242 myfunc := func() bool {
243   return x > 10000
244 }
245 ```
246 {: data-line="1"}
247
248 Functions are first class objects.
249
250 ### Multiple return types
251
252 ```go
253 a, b := getMessage()
254 ```
255
256 ```go
257 func getMessage() (a string, b string) {
258   return "Hello", "World"
259 }
260 ```
261 {: data-line="2"}
262
263
264 ### Named return values
265
266 ```go
267 func split(sum int) (x, y int) {
268   x = sum * 4 / 9
269   y = sum - x
270   return
271 }
272 ```
273 {: data-line="4"}
274
275 By defining the return value names in the signature, a `return` (no args) will return variables with those names.
276
277 See: [Named return values](https://tour.golang.org/basics/7)
278
279 ## Packages
280 {: .-three-column}
281
282 ### Importing
283
284 ```go
285 import "fmt"
286 import "math/rand"
287 ```
288
289 ```go
290 import (
291   "fmt"        // gives fmt.Println
292   "math/rand"  // gives rand.Intn
293 )
294 ```
295
296 Both are the same.
297
298 See: [Importing](https://tour.golang.org/basics/1)
299
300 ### Aliases
301
302 ```go
303 import r "math/rand"
304 ```
305 {: data-line="1"}
306
307 ```go
308 r.Intn()
309 ```
310
311 ### Exporting names
312
313 ```go
314 func Hello () {
315   ยทยทยท
316 }
317 ```
318
319 Exported names begin with capital letters.
320
321 See: [Exported names](https://tour.golang.org/basics/3)
322
323 ### Packages
324
325 ```go
326 package hello
327 ```
328
329 Every package file has to start with `package`.
330
331 ## Concurrency
332 {: .-three-column}
333
334 ### Goroutines
335
336 ```go
337 func main() {
338   // A "channel"
339   ch := make(chan string)
340
341   // Start concurrent routines
342   go push("Moe", ch)
343   go push("Larry", ch)
344   go push("Curly", ch)
345
346   // Read 3 results
347   // (Since our goroutines are concurrent,
348   // the order isn't guaranteed!)
349   fmt.Println(<-ch, <-ch, <-ch)
350 }
351 ```
352 {: data-line="3,6,7,8,13"}
353
354 ```go
355 func push(name string, ch chan string) {
356   msg := "Hey, " + name
357   ch <- msg
358 }
359 ```
360 {: data-line="3"}
361
362 Channels are concurrency-safe communication objects, used in goroutines.
363
364 See: [Goroutines](https://tour.golang.org/concurrency/1), [Channels](https://tour.golang.org/concurrency/2)
365
366 ### Buffered channels
367
368 ```go
369 ch := make(chan int, 2)
370 ch <- 1
371 ch <- 2
372 ch <- 3
373 // fatal error:
374 // all goroutines are asleep - deadlock!
375 ```
376 {: data-line="1"}
377
378 Buffered channels limit the amount of messages it can keep.
379
380 See: [Buffered channels](https://tour.golang.org/concurrency/3)
381
382 ### Closing channels
383
384 #### Closes a channel
385
386 ```go
387 ch <- 1
388 ch <- 2
389 ch <- 3
390 close(ch)
391 ```
392 {: data-line="4"}
393
394 #### Iterates across a channel until its closed
395
396 ```go
397 for i := range ch {
398   ยทยทยท
399 }
400 ```
401 {: data-line="1"}
402
403 #### Closed if `ok == false`
404
405 ```go
406 v, ok := <- ch
407 ```
408
409 See: [Range and close](https://tour.golang.org/concurrency/4)
410
411 ### WaitGroup
412
413 ```go
414 import "sync"
415
416 func main() {
417   var wg sync.WaitGroup
418   
419   for _, item := range itemList {
420     // Increment WaitGroup Counter
421     wg.Add(1)
422     go doOperation(item)
423   }
424   // Wait for goroutines to finish
425   wg.Wait()
426   
427 }
428 ```
429 {: data-line="1,4,8,12"}
430
431 ```go
432 func doOperation(item string) {
433   defer wg.Done()
434   // do operation on item
435   // ...
436 }
437 ```
438 {: data-line="2"}
439
440 A WaitGroup waits for a collection of goroutines to finish. The main goroutine calls Add to set the number of goroutines to wait for. The goroutine calls `wg.Done()` when it finishes.
441 See: [WaitGroup](https://golang.org/pkg/sync/#WaitGroup)
442
443
444 ## Error control
445
446 ### Defer
447
448 ```go
449 func main() {
450   defer fmt.Println("Done")
451   fmt.Println("Working...")
452 }
453 ```
454 {: data-line="2"}
455
456 Defers running a function until the surrounding function returns.
457 The arguments are evaluated immediately, but the function call is not ran until later.
458
459 See: [Defer, panic and recover](https://blog.golang.org/defer-panic-and-recover)
460
461 ### Deferring functions
462
463 ```go
464 func main() {
465   defer func() {
466     fmt.Println("Done")
467   }()
468   fmt.Println("Working...")
469 }
470 ```
471 {: data-line="2,3,4"}
472
473 Lambdas are better suited for defer blocks.
474
475 ```go
476 func main() {
477   var d = int64(0)
478   defer func(d *int64) {
479     fmt.Printf("& %v Unix Sec\n", *d)
480   }(&d)
481   fmt.Print("Done ")
482   d = time.Now().Unix()
483 }
484 ```
485 {: data-line="3,4,5"}
486 The defer func uses current value of d, unless we use a pointer to get final value at end of main.
487
488 ## Structs
489 {: .-three-column}
490
491 ### Defining
492
493 ```go
494 type Vertex struct {
495   X int
496   Y int
497 }
498 ```
499 {: data-line="1,2,3,4"}
500
501 ```go
502 func main() {
503   v := Vertex{1, 2}
504   v.X = 4
505   fmt.Println(v.X, v.Y)
506 }
507 ```
508
509 See: [Structs](https://tour.golang.org/moretypes/2)
510
511 ### Literals
512
513 ```go
514 v := Vertex{X: 1, Y: 2}
515 ```
516
517 ```go
518 // Field names can be omitted
519 v := Vertex{1, 2}
520 ```
521
522 ```go
523 // Y is implicit
524 v := Vertex{X: 1}
525 ```
526
527 You can also put field names.
528
529 ### Pointers to structs
530
531 ```go
532 v := &Vertex{1, 2}
533 v.X = 2
534 ```
535
536 Doing `v.X` is the same as doing `(*v).X`, when `v` is a pointer.
537
538 ## Methods
539
540 ### Receivers
541
542 ```go
543 type Vertex struct {
544   X, Y float64
545 }
546 ```
547
548 ```go
549 func (v Vertex) Abs() float64 {
550   return math.Sqrt(v.X * v.X + v.Y * v.Y)
551 }
552 ```
553 {: data-line="1"}
554
555 ```go
556 v := Vertex{1, 2}
557 v.Abs()
558 ```
559
560 There are no classes, but you can define functions with _receivers_.
561
562 See: [Methods](https://tour.golang.org/methods/1)
563
564 ### Mutation
565
566 ```go
567 func (v *Vertex) Scale(f float64) {
568   v.X = v.X * f
569   v.Y = v.Y * f
570 }
571 ```
572 {: data-line="1"}
573
574 ```go
575 v := Vertex{6, 12}
576 v.Scale(0.5)
577 // `v` is updated
578 ```
579
580 By defining your receiver as a pointer (`*Vertex`), you can do mutations.
581
582 See: [Pointer receivers](https://tour.golang.org/methods/4)
583
584 ## Interfaces
585
586 ### A basic interface
587
588 ```go
589 type Shape interface {
590   Area() float64
591   Perimeter() float64
592 }
593 ```
594
595 ### Struct
596
597 ```go
598 type Rectangle struct {
599   Length, Width float64
600 }
601 ```
602
603 Struct `Rectangle` implicitly implements interface `Shape` by implementing all of its methods.
604
605 ### Methods
606
607 ```go
608 func (r Rectangle) Area() float64 {
609   return r.Length * r.Width
610 }
611
612 func (r Rectangle) Perimeter() float64 {
613   return 2 * (r.Length + r.Width)
614 }
615 ```
616
617 The methods defined in `Shape` are implemented in `Rectangle`.
618
619 ### Interface example
620
621 ```go
622 func main() {
623   var r Shape = Rectangle{Length: 3, Width: 4}
624   fmt.Printf("Type of r: %T, Area: %v, Perimeter: %v.", r, r.Area(), r.Perimeter())
625 }
626 ```
627
628 ## References
629
630 ### Official resources
631 {: .-intro}
632
633 - [A tour of Go](https://tour.golang.org/welcome/1) _(tour.golang.org)_
634 - [Golang wiki](https://github.com/golang/go/wiki/) _(github.com)_
635 - [Effective Go](https://golang.org/doc/effective_go.html) _(golang.org)_
636
637 ### Other links
638 {: .-intro}
639
640 - [Go by Example](https://gobyexample.com/) _(gobyexample.com)_
641 - [Awesome Go](https://awesome-go.com/) _(awesome-go.com)_
642 - [JustForFunc Youtube](https://www.youtube.com/channel/UC_BzFbxG2za3bp5NRRRXJSw) _(youtube.com)_
643 - [Style Guide](https://github.com/golang/go/wiki/CodeReviewComments) _(github.com)_