Foundations
Variables
Go variables hold typed values that can feed later expressions.
variable
`var` declares a variable. Go infers the type from the value when no explicit type is written.
Variables
variables.go
Replay: real traced execution (multi-file project)
package main
import "fmt"
func main() {
var unitPrice = 12
quantity := 3
total := unitPrice * quantity
fmt.Println("unit=", unitPrice)
fmt.Println("total=", total)
}
package main
import "fmt"
func main() {
var unitPrice = 8
quantity := 3
total := unitPrice * quantity
fmt.Println("unit=", unitPrice)
fmt.Println("total=", total)
}
package main
import "fmt"
func main() {
var unitPrice = 20
quantity := 3
total := unitPrice * quantity
fmt.Println("unit=", unitPrice)
fmt.Println("total=", total)
}
unitPrice ← 12, quantity ← 3, total ← 36
5func main() {6 var unitPrice→ 12 = 12 //@unitPrice=8, 207 quantity→ 3 := 38 total→ 36 := unitPrice12 * quantity3910 fmt.Println("unit=", unitPrice12)11 fmt.Println("total=", total36)12}outputunit= 12 total= 36
unitPrice ← 8, quantity ← 3, total ← 24
5func main() {6 var unitPrice→ 8 = 87 quantity→ 3 := 38 total→ 24 := unitPrice8 * quantity3910 fmt.Println("unit=", unitPrice8)11 fmt.Println("total=", total24)12}outputunit= 8 total= 24
unitPrice ← 20, quantity ← 3, total ← 60
5func main() {6 var unitPrice→ 20 = 207 quantity→ 3 := 38 total→ 60 := unitPrice20 * quantity3910 fmt.Println("unit=", unitPrice20)11 fmt.Println("total=", total60)12}outputunit= 20 total= 60
Follow the Total
unitPricestarts at12.quantitystarts at3.total := unitPrice * quantitymultiplies12 * 3.totalbecomes36.- The program prints
unit= 12andtotal= 36. | unitPrice | quantity | total | | --- | --- | --- | | 8 | 3 | 24 | | 12 | 3 | 36 | | 20 | 3 | 60 |
Exercise: variables.go
Reproduce unit= 12 and total= 36, then try unitPrice 8 and 20 and predict each total before running it.