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)
246 See: [Go's "while"](https://tour.golang.org/flowcontrol/3)
254 myfunc := func() bool {
260 Functions are first class objects.
262 ### Multiple return types
269 func getMessage() (a string, b string) {
270 return "Hello", "World"
276 ### Named return values
279 func split(sum int) (x, y int) {
287 By defining the return value names in the signature, a `return` (no args) will return variables with those names.
289 See: [Named return values](https://tour.golang.org/basics/7)
303 "fmt" // gives fmt.Println
304 "math/rand" // gives rand.Intn
310 See: [Importing](https://tour.golang.org/basics/1)
331 Exported names begin with capital letters.
333 See: [Exported names](https://tour.golang.org/basics/3)
341 Every package file has to start with `package`.
351 ch := make(chan string)
353 // Start concurrent routines
359 // (Since our goroutines are concurrent,
360 // the order isn't guaranteed!)
361 fmt.Println(<-ch, <-ch, <-ch)
364 {: data-line="3,6,7,8,13"}
367 func push(name string, ch chan string) {
368 msg := "Hey, " + name
374 Channels are concurrency-safe communication objects, used in goroutines.
376 See: [Goroutines](https://tour.golang.org/concurrency/1), [Channels](https://tour.golang.org/concurrency/2)
378 ### Buffered channels
381 ch := make(chan int, 2)
386 // all goroutines are asleep - deadlock!
390 Buffered channels limit the amount of messages it can keep.
392 See: [Buffered channels](https://tour.golang.org/concurrency/3)
396 #### Closes a channel
406 #### Iterates across a channel until its closed
415 #### Closed if `ok == false`
421 See: [Range and close](https://tour.golang.org/concurrency/4)
429 var wg sync.WaitGroup
431 for _, item := range itemList {
432 // Increment WaitGroup Counter
436 // Wait for goroutines to finish
441 {: data-line="1,4,8,12"}
444 func doOperation(item string) {
446 // do operation on item
452 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.
453 See: [WaitGroup](https://golang.org/pkg/sync/#WaitGroup)
462 defer fmt.Println("Done")
463 fmt.Println("Working...")
468 Defers running a function until the surrounding function returns.
469 The arguments are evaluated immediately, but the function call is not ran until later.
471 See: [Defer, panic and recover](https://blog.golang.org/defer-panic-and-recover)
473 ### Deferring functions
480 fmt.Println("Working...")
483 {: data-line="2,3,4"}
485 Lambdas are better suited for defer blocks.
490 defer func(d *int64) {
491 fmt.Printf("& %v Unix Sec\n", *d)
494 d = time.Now().Unix()
497 {: data-line="3,4,5"}
498 The defer func uses current value of d, unless we use a pointer to get final value at end of main.
511 {: data-line="1,2,3,4"}
517 fmt.Println(v.X, v.Y)
521 See: [Structs](https://tour.golang.org/moretypes/2)
526 v := Vertex{X: 1, Y: 2}
530 // Field names can be omitted
539 You can also put field names.
541 ### Pointers to structs
548 Doing `v.X` is the same as doing `(*v).X`, when `v` is a pointer.
561 func (v Vertex) Abs() float64 {
562 return math.Sqrt(v.X * v.X + v.Y * v.Y)
572 There are no classes, but you can define functions with _receivers_.
574 See: [Methods](https://tour.golang.org/methods/1)
579 func (v *Vertex) Scale(f float64) {
592 By defining your receiver as a pointer (`*Vertex`), you can do mutations.
594 See: [Pointer receivers](https://tour.golang.org/methods/4)
598 ### A basic interface
601 type Shape interface {
610 type Rectangle struct {
611 Length, Width float64
615 Struct `Rectangle` implicitly implements interface `Shape` by implementing all of its methods.
620 func (r Rectangle) Area() float64 {
621 return r.Length * r.Width
624 func (r Rectangle) Perimeter() float64 {
625 return 2 * (r.Length + r.Width)
629 The methods defined in `Shape` are implemented in `Rectangle`.
631 ### Interface example
635 var r Shape = Rectangle{Length: 3, Width: 4}
636 fmt.Printf("Type of r: %T, Area: %v, Perimeter: %v.", r, r.Area(), r.Perimeter())
642 ### Official resources
645 - [A tour of Go](https://tour.golang.org/welcome/1) _(tour.golang.org)_
646 - [Golang wiki](https://github.com/golang/go/wiki/) _(github.com)_
647 - [Effective Go](https://golang.org/doc/effective_go.html) _(golang.org)_
652 - [Go by Example](https://gobyexample.com/) _(gobyexample.com)_
653 - [Awesome Go](https://awesome-go.com/) _(awesome-go.com)_
654 - [JustForFunc Youtube](https://www.youtube.com/channel/UC_BzFbxG2za3bp5NRRRXJSw) _(youtube.com)_
655 - [Style Guide](https://github.com/golang/go/wiki/CodeReviewComments) _(github.com)_