Go by Example: Basic Arithmetic
Perform arithmetic operations in Go with this comprehensive example. It covers addition, subtraction, multiplication, division, and modulus, while also highlighting important concepts like integer vs. floating-point division and the necessity of explicit type conversions in mixed-type operations.
Code
package main
import "fmt"
func main() {
// Integer arithmetic
a, b := 10, 3
fmt.Println("Addition:", a + b)
fmt.Println("Subtraction:", a - b)
fmt.Println("Multiplication:", a * b)
fmt.Println("Division:", a / b)
fmt.Println("Modulus:", a % b)
// Float arithmetic
x, y := 10.0, 3.0
fmt.Println("Float Division:", x / y)
// Type conversion
result := float64(a) / float64(b)
fmt.Println("Converted Division:", result)
}Explanation
Go supports all standard arithmetic operations with behavior strictly determined by operand types. The language enforces strong typing without implicit conversions, a design choice that eliminates an entire class of subtle bugs at the cost of requiring more explicit code. This explicitness is considered a feature, not a bug—it makes the programmer's intent perfectly clear.
Integer division in Go truncates toward zero, discarding any fractional part. This means 10 / 3 yields 3, not 3.333.... The modulus operator % returns the remainder, so 10 % 3 gives 1. For floating-point division that preserves decimal precision, both operands must be floating-point types (float32 or float64).
Go's type system prohibits mixing numeric types in arithmetic operations. You cannot add an int to a float64 directly—explicit conversion is mandatory. Type conversion uses the syntax T(value) where T is the target type. For example, float64(10) converts the integer 10 to a float64. This requirement eliminates ambiguity about precision and prevents accidental data loss, though it requires more verbose code when working with mixed numeric types.

