Understand the contract
Go gives every variable a static type. Common choices include int for ordinary integer calculations, float64 for approximate real-number arithmetic, bool for conditions and string for text. Fixed-width types such as int64 and uint32 are useful when a data format requires a specific width.
int has an implementation-dependent size of 32 or 64 bits. A byte is an alias for uint8 and a rune is an alias for int32. These names communicate intent when working with encoded text. A string stores bytes, so its length is not necessarily a count of visible characters.
Work through the example
The example prints 2 for integer division and 2.5 when both operands are converted to float64. Printf with %T reveals the type of each argument. Go does not automatically mix unrelated numeric variable types, even if their current values appear compatible.
package main
import "fmt"
func main() {
total, count := 5, 2
fmt.Println(total / count)
fmt.Println(float64(total) / float64(count))
fmt.Printf("%T %T\n", total, float64(total))
}Watch this boundary
Binary floating-point does not represent every decimal fraction exactly. For a money exercise, store a defined smallest unit as an integer and document the rounding rule. Unsigned integers also wrap during arithmetic; choosing uint does not substitute for checking a business rule such as a nonnegative balance.
Practice with a changed input
Print the types of a string, a rune literal and a byte variable. Compare 5/2, float64(5/2) and float64(5)/2 and explain when information was lost.
Lesson 8 of 50
View the full Go basics seriesReferences & further reading
Need help with your Go backend?
I work with engineering teams on focused Go and Kubernetes platform engagements, with limited consulting availability.
Explore Go consulting services