DMarlon Studio

Lesson 3 · 3 of 20

Constants and arithmetic · Go

Use constants and iota in Go, calculate with + - * / and %, and convert between int and float64 so you keep the decimals.

Go · Constants and arithmetic in DMarlon Studio: the example's code and its output in the terminal

A constant is declared with const and its value cannot change: vatRate = 0.21 is the VAT rate. Several constants can be grouped between parentheses and, inside the group, iota is 0 on the first one, 1 on the next, and so on: Small, Medium and Large are 0, 1 and 2.

Between two integers, / does integer division: 7/3 gives 2, with no decimals. % gives the remainder: 7%3 is 1, the pizza left over.

Go never mixes types on its own: price * pizzas would be an error, because one is a float64 and the other an int. You have to convert explicitly with float64(pizzas). With both converted, float64(pizzas) / float64(guests) gives 2.3333333333333335, with all its decimals.

price * float64(pizzas) gives the total, 87.5, and multiplying it by the constant gives the VAT. The shorthand operators update a variable in place: count += 5 is count = count + 5, count *= 2 doubles it and count++ adds one. It goes from 10 to 15, 30 and 31.

Code · main.go

package mainimport "fmt"// A constant never changes.const vatRate = 0.21// iota numbers the constants of a group: 0, 1, 2...const (	Small = iota	Medium	Large)func main() {	pizzas, guests := 7, 3	fmt.Println("Pizzas per guest:", pizzas/guests) // int / int drops decimals	fmt.Println("Pizzas left over:", pizzas%guests) // % is the remainder	// Mixing int and float64 needs a conversion.	share := float64(pizzas) / float64(guests)	fmt.Println("Exact share:", share)	price := 12.5	total := price * float64(pizzas)	fmt.Println("Total:", total, "VAT:", total*vatRate)	count := 10	count += 5 // count = count + 5	count *= 2	count++	fmt.Println("Counter:", count)	fmt.Println("Sizes:", Small, Medium, Large)}

Output · go run main.go

Pizzas per guest: 2
Pizzas left over: 1
Exact share: 2.3333333333333335
Total: 87.5 VAT: 18.375
Counter: 31
Sizes: 0 1 2

Key points

  • const declares values that never change.
  • iota numbers the constants of a group from 0.
  • int / int drops the decimals; % gives the remainder.
  • To mix int and float64 you convert: float64(x).
  • +=, -=, *=, /= and ++ shorten the operations.

Exercise

With a constant boxPrice = 2.40, work out how many boxes of 6 eggs you can fill with 75 eggs, how many eggs are left and what the full boxes cost.