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
54 var msg = "Hello, world!"
55 var msg string = "Hello, world!"
58 var x, msg = 1, "Hello, world!"
74 #### Shortcut of above (Infers type)
85 const Size int64 = 1024
102 Constants can be character, string, boolean, or numeric values.
104 See: [Constants](https://tour.golang.org/basics/15)
120 Strings are of type `string`.
129 num := 3 + 4i // complex128
130 num := byte('a') // byte (alias for uint8)
136 var u uint = 7 // uint (unsigned)
137 var p float32 = 22.7 // 32-bit float
143 // var numbers [5]int
144 numbers := [...]int{0, 0, 0, 0, 0}
147 Arrays have a fixed size.
152 slice := []int{2, 3, 4}
156 slice := []byte("Hello")
159 Slices have a dynamic size, unlike arrays.
166 fmt.Println("Value is", b)
172 func getPointer () (myPointer *int) {
185 Pointers point to a memory location of a variable. Go is fully garbage-collected.
187 See: [Pointers](https://tour.golang.org/moretypes/1)
197 See: [Type conversions](https://tour.golang.org/basics/13)
205 if day == "sunday" || day == "saturday" {
207 } else if day == "monday" && isTired() {
213 {: data-line="1,3,5"}
215 See: [If](https://tour.golang.org/flowcontrol/5)
220 if _, err := doThing(); err != nil {
226 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`.
228 See: [If with a short statement](https://tour.golang.org/flowcontrol/6)
235 // cases don't "fall through" by default!
246 See: [Switch](https://github.com/golang/go/wiki/Switch)
251 for count := 0; count <= 10; count++ {
252 fmt.Println("My counter is at", count)
256 See: [For loops](https://tour.golang.org/flowcontrol/1)
261 entry := []string{"Jack","John","Jones"}
262 for i, val := range entry {
263 fmt.Printf("At position %d, the character %s is present\n", i, val)
267 See: [For-Range loops](https://gobyexample.com/range)
279 See: [Go's "while"](https://tour.golang.org/flowcontrol/3)
287 myfunc := func() bool {
293 Functions are first class objects.
295 ### Multiple return types
302 func getMessage() (a string, b string) {
303 return "Hello", "World"
309 ### Named return values
312 func split(sum int) (x, y int) {
320 By defining the return value names in the signature, a `return` (no args) will return variables with those names.
322 See: [Named return values](https://tour.golang.org/basics/7)
336 "fmt" // gives fmt.Println
337 "math/rand" // gives rand.Intn
343 See: [Importing](https://tour.golang.org/basics/1)
364 Exported names begin with capital letters.
366 See: [Exported names](https://tour.golang.org/basics/3)
374 Every package file has to start with `package`.
384 ch := make(chan string)
386 // Start concurrent routines
392 // (Since our goroutines are concurrent,
393 // the order isn't guaranteed!)
394 fmt.Println(<-ch, <-ch, <-ch)
397 {: data-line="3,6,7,8,13"}
400 func push(name string, ch chan string) {
401 msg := "Hey, " + name
407 Channels are concurrency-safe communication objects, used in goroutines.
409 See: [Goroutines](https://tour.golang.org/concurrency/1), [Channels](https://tour.golang.org/concurrency/2)
411 ### Buffered channels
414 ch := make(chan int, 2)
419 // all goroutines are asleep - deadlock!
423 Buffered channels limit the amount of messages it can keep.
425 See: [Buffered channels](https://tour.golang.org/concurrency/3)
429 #### Closes a channel
439 #### Iterates across a channel until its closed
448 #### Closed if `ok == false`
454 See: [Range and close](https://tour.golang.org/concurrency/4)
462 var wg sync.WaitGroup
464 for _, item := range itemList {
465 // Increment WaitGroup Counter
467 go doOperation(&wg, item)
469 // Wait for goroutines to finish
474 {: data-line="1,4,8,12"}
477 func doOperation(wg *sync.WaitGroup, item string) {
479 // do operation on item
485 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.
486 See: [WaitGroup](https://golang.org/pkg/sync/#WaitGroup)
495 defer fmt.Println("Done")
496 fmt.Println("Working...")
501 Defers running a function until the surrounding function returns.
502 The arguments are evaluated immediately, but the function call is not ran until later.
504 See: [Defer, panic and recover](https://blog.golang.org/defer-panic-and-recover)
506 ### Deferring functions
513 fmt.Println("Working...")
516 {: data-line="2,3,4"}
518 Lambdas are better suited for defer blocks.
523 defer func(d *int64) {
524 fmt.Printf("& %v Unix Sec\n", *d)
527 d = time.Now().Unix()
530 {: data-line="3,4,5"}
531 The defer func uses current value of d, unless we use a pointer to get final value at end of main.
544 {: data-line="1,2,3,4"}
550 fmt.Println(v.X, v.Y)
554 See: [Structs](https://tour.golang.org/moretypes/2)
559 v := Vertex{X: 1, Y: 2}
563 // Field names can be omitted
572 You can also put field names.
574 ### Pointers to structs
581 Doing `v.X` is the same as doing `(*v).X`, when `v` is a pointer.
594 func (v Vertex) Abs() float64 {
595 return math.Sqrt(v.X * v.X + v.Y * v.Y)
605 There are no classes, but you can define functions with _receivers_.
607 See: [Methods](https://tour.golang.org/methods/1)
612 func (v *Vertex) Scale(f float64) {
625 By defining your receiver as a pointer (`*Vertex`), you can do mutations.
627 See: [Pointer receivers](https://tour.golang.org/methods/4)
631 ### A basic interface
634 type Shape interface {
643 type Rectangle struct {
644 Length, Width float64
648 Struct `Rectangle` implicitly implements interface `Shape` by implementing all of its methods.
653 func (r Rectangle) Area() float64 {
654 return r.Length * r.Width
657 func (r Rectangle) Perimeter() float64 {
658 return 2 * (r.Length + r.Width)
662 The methods defined in `Shape` are implemented in `Rectangle`.
664 ### Interface example
668 var r Shape = Rectangle{Length: 3, Width: 4}
669 fmt.Printf("Type of r: %T, Area: %v, Perimeter: %v.", r, r.Area(), r.Perimeter())
675 ### Official resources
678 - [A tour of Go](https://tour.golang.org/welcome/1) _(tour.golang.org)_
679 - [Golang wiki](https://github.com/golang/go/wiki/) _(github.com)_
680 - [Effective Go](https://golang.org/doc/effective_go.html) _(golang.org)_
685 - [Go by Example](https://gobyexample.com/) _(gobyexample.com)_
686 - [Awesome Go](https://awesome-go.com/) _(awesome-go.com)_
687 - [JustForFunc Youtube](https://www.youtube.com/channel/UC_BzFbxG2za3bp5NRRRXJSw) _(youtube.com)_
688 - [Style Guide](https://github.com/golang/go/wiki/CodeReviewComments) _(github.com)_