4 prism_languages: [go, bash]
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)_
33 message := greetMe("world")
37 func greetMe(name string) string {
38 return "Hello, " + name + "!"
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).
50 #### Variable declaration
57 #### Shortcut of above (Infers type)
69 Constants can be character, string, boolean, or numeric values.
71 See: [Constants](https://tour.golang.org/basics/15)
87 Strings are of type `string`.
96 num := 3 + 4i // complex128
97 num := byte('a') // byte (alias for uint8)
103 var u uint = 7 // uint (unsigned)
104 var p float32 = 22.7 // 32-bit float
110 // var numbers [5]int
111 numbers := [...]int{0, 0, 0, 0, 0}
114 Arrays have a fixed size.
119 slice := []int{2, 3, 4}
123 slice := []byte("Hello")
126 Slices have a dynamic size, unlike arrays.
133 fmt.Println("Value is", b)
139 func getPointer () (myPointer *int) {
152 Pointers point to a memory location of a variable. Go is fully garbage-collected.
154 See: [Pointers](https://tour.golang.org/moretypes/1)
164 See: [Type conversions](https://tour.golang.org/basics/13)
172 if day == "sunday" || day == "saturday" {
174 } else if day == "monday" && isTired() {
180 {: data-line="1,3,5"}
182 See: [If](https://tour.golang.org/flowcontrol/5)
187 if _, err := doThing(); err != nil {
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`.
195 See: [If with a short statement](https://tour.golang.org/flowcontrol/6)
202 // cases don't "fall through" by default!
213 See: [Switch](https://github.com/golang/go/wiki/Switch)
218 for count := 0; count <= 10; count++ {
219 fmt.Println("My counter is at", count)
223 See: [For loops](https://tour.golang.org/flowcontrol/1)
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)
234 See: [For-Range loops](https://gobyexample.com/range)
242 myfunc := func() bool {
248 Functions are first class objects.
250 ### Multiple return types
257 func getMessage() (a string, b string) {
258 return "Hello", "World"
264 ### Named return values
267 func split(sum int) (x, y int) {
275 By defining the return value names in the signature, a `return` (no args) will return variables with those names.
277 See: [Named return values](https://tour.golang.org/basics/7)
291 "fmt" // gives fmt.Println
292 "math/rand" // gives rand.Intn
298 See: [Importing](https://tour.golang.org/basics/1)
319 Exported names begin with capital letters.
321 See: [Exported names](https://tour.golang.org/basics/3)
329 Every package file has to start with `package`.
339 ch := make(chan string)
341 // Start concurrent routines
347 // (Since our goroutines are concurrent,
348 // the order isn't guaranteed!)
349 fmt.Println(<-ch, <-ch, <-ch)
352 {: data-line="3,6,7,8,13"}
355 func push(name string, ch chan string) {
356 msg := "Hey, " + name
362 Channels are concurrency-safe communication objects, used in goroutines.
364 See: [Goroutines](https://tour.golang.org/concurrency/1), [Channels](https://tour.golang.org/concurrency/2)
366 ### Buffered channels
369 ch := make(chan int, 2)
374 // all goroutines are asleep - deadlock!
378 Buffered channels limit the amount of messages it can keep.
380 See: [Buffered channels](https://tour.golang.org/concurrency/3)
384 #### Closes a channel
394 #### Iterates across a channel until its closed
403 #### Closed if `ok == false`
409 See: [Range and close](https://tour.golang.org/concurrency/4)
417 var wg sync.WaitGroup
419 for _, item := range itemList {
420 // Increment WaitGroup Counter
424 // Wait for goroutines to finish
429 {: data-line="1,4,8,12"}
432 func doOperation(item string) {
434 // do operation on item
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)
450 defer fmt.Println("Done")
451 fmt.Println("Working...")
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.
459 See: [Defer, panic and recover](https://blog.golang.org/defer-panic-and-recover)
461 ### Deferring functions
468 fmt.Println("Working...")
471 {: data-line="2,3,4"}
473 Lambdas are better suited for defer blocks.
478 defer func(d *int64) {
479 fmt.Printf("& %v Unix Sec\n", *d)
482 d = time.Now().Unix()
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.
499 {: data-line="1,2,3,4"}
505 fmt.Println(v.X, v.Y)
509 See: [Structs](https://tour.golang.org/moretypes/2)
514 v := Vertex{X: 1, Y: 2}
518 // Field names can be omitted
527 You can also put field names.
529 ### Pointers to structs
536 Doing `v.X` is the same as doing `(*v).X`, when `v` is a pointer.
549 func (v Vertex) Abs() float64 {
550 return math.Sqrt(v.X * v.X + v.Y * v.Y)
560 There are no classes, but you can define functions with _receivers_.
562 See: [Methods](https://tour.golang.org/methods/1)
567 func (v *Vertex) Scale(f float64) {
580 By defining your receiver as a pointer (`*Vertex`), you can do mutations.
582 See: [Pointer receivers](https://tour.golang.org/methods/4)
586 ### A basic interface
589 type Shape interface {
598 type Rectangle struct {
599 Length, Width float64
603 Struct `Rectangle` implicitly implements interface `Shape` by implementing all of its methods.
608 func (r Rectangle) Area() float64 {
609 return r.Length * r.Width
612 func (r Rectangle) Perimeter() float64 {
613 return 2 * (r.Length + r.Width)
617 The methods defined in `Shape` are implemented in `Rectangle`.
619 ### Interface example
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())
630 ### Official resources
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)_
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)_