Post

Compile

1
2
3
4
5
6
go build main.go
./main

go run main.go

Variable and Type

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
package main

import "fmt"

func main() {

  // variable
  var stationName string
  var nextTrainTime int8
  var isUptownTrain bool
  
  stationName = "Union Square"
  nextTrainTime = 12
  isUptownTrain = false
  
  fmt.Println("Current station:", stationName)
  fmt.Println("Next train:", nextTrainTime, "minutes")
  fmt.Println("Is uptown:", isUptownTrain)
  
  stationName = "Grand Central"
  nextTrainTime = 3
  isUptownTrain = true
  
  fmt.Println("")
  fmt.Println("Current station:", stationName)
  fmt.Println("Next train:", nextTrainTime, "minutes")
  fmt.Println("Is uptown:", isUptownTrain)

  myvar := "my variable"

  var flavorScale float32 = 5.8

  const earthsGravity = 9.80665


  // if statement
  if isHungry := false; isHungry {
    fmt.Println("Eat the cookie") 
  } else {
    fmt.Println("Step away from the cookie...")
  }

  // switch statement
  switch clothingChoice := "sweater"; clothingChoice {
  case "shirt":
    fmt.Println("We have shirts in S and M only.")
  case "polos":
    fmt.Println("We have polos in M, L, and XL.")
  case "sweater":
    fmt.Println("We have sweaters in S, M, L, and XL.")
  case "jackets":
    fmt.Println("We have jackets in all sizes.")
  default:
    fmt.Println("Sorry, we don't carry that")
  }

  // random
  rand.Seed(time.Now().UnixNano())
  amountLeft := rand.Intn(10000)

  // pointer and reference
  lyrics := "Moments so dear" 
  pointerForStr := &lyrics

  *pointerForStr = "Journeys to plan" 

  fmt.Println(lyrics) // Prints: Journeys to plan
}

// function example
func multiplier(x, y int32) (int32, int32, int32) {
  return x * y, x, y
}

// defer statement
// avoid logging at each return
func calculateTaxes(revenue, deductions, credits float64) float64 {
  defer fmt.Println("Taxes Calculated!")
  taxRate := .06143
  fmt.Println("Calculating Taxes")

  if deductions == 0 || credits == 0 {
    return revenue * taxRate
  }
  

  taxValue := (revenue - (deductions * credits)) * taxRate
  if taxValue >= 0 {
    return taxValue
  } else {
    return 0
  }
}
This post is licensed under CC BY 4.0 by the author.