Data Types
Numeric Types
Go has integer and floating-point numbers for different kinds of arithmetic.
numeric type
Numeric variables can use concrete types such as `int` and `float64`.
Numeric Types
numeric_types.go
Replay: real traced execution (multi-file project)
package main
import "fmt"
func main() {
var count = 6
var price float64 = 2.5
total := float64(count) * price
fmt.Println("count=", count)
fmt.Println("total=", total)
}
package main
import "fmt"
func main() {
var count = 3
var price float64 = 2.5
total := float64(count) * price
fmt.Println("count=", count)
fmt.Println("total=", total)
}
package main
import "fmt"
func main() {
var count = 10
var price float64 = 2.5
total := float64(count) * price
fmt.Println("count=", count)
fmt.Println("total=", total)
}
count ← 6, price ← 2.5, total ← 15
5func main() {6 var count→ 6 = 6 //@count=3, 107 var price→ 2.5 float64 = 2.58 total→ 15 := float64(count6) * price2.5910 fmt.Println("count=", count6)11 fmt.Println("total=", total15)12}outputcount= 6 total= 15
count ← 3, price ← 2.5, total ← 7.5
5func main() {6 var count→ 3 = 37 var price→ 2.5 float64 = 2.58 total→ 7.5 := float64(count3) * price2.5910 fmt.Println("count=", count3)11 fmt.Println("total=", total7.5)12}outputcount= 3 total= 7.5
count ← 10, price ← 2.5, total ← 25
5func main() {6 var count→ 10 = 107 var price→ 2.5 float64 = 2.58 total→ 25 := float64(count10) * price2.5910 fmt.Println("count=", count10)11 fmt.Println("total=", total25)12}outputcount= 10 total= 25
Follow the Numbers
countstarts at6.priceis2.5.float64(count)makes the integer usable with the floating-point price.total := float64(count) * pricebecomes15.- The program prints
count= 6andtotal= 15. | count | price | total | | --- | --- | --- | | 3 | 2.5 | 7.5 | | 6 | 2.5 | 15 | | 10 | 2.5 | 25 |
Exercise: numeric_types.go
Reproduce total= 15, then use the pinned counts 3 and 10 to predict each total.