BudiBadu Logo

Samplebadu

Code with Example
BudiBadu Logo
Samplebadu

Go by Example: Basic Arithmetic

Go 1.23

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.

Code Breakdown

7-12
Integer arithmetic operations. Note that division (10 / 3) results in 3, not 3.333..., because both operands are integers. The modulus operator (%) returns the remainder of division, which is 1 in this case (10 = 3*3 + 1).
15-16
Floating-point arithmetic. When both operands are floats, division preserves the decimal part. 10.0 / 3.0 gives approximately 3.333... This is the key difference from integer division.
19
Explicit type conversion for mixed-type arithmetic. We convert both integers to float64 before division to get a floating-point result. Go requires explicit conversion - you cannot mix int and float64 directly in arithmetic operations.