Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The % operator in Go is the arithmetic remainder operator. It yields the remainder of the division between two integer operands.
package main

import "fmt"

func main() {
    dividend := 10
    divisor := 3
    result := dividend % divisor
    
    fmt.Println(result) // Output: 1
}

Type Constraints

In Go, the % operator is strictly restricted to integer types (int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, uintptr, byte, rune). Attempting to use the % operator with floating-point numbers (float32, float64) or complex numbers results in an “operator not defined” compile-time error (e.g., invalid operation: a % b (operator % not defined on float64)). To calculate the remainder of floating-point numbers, Go requires the math.Mod function from the standard library.

Mathematical Behavior and Sign Rules

Go implements truncated division (rounding toward zero). Because of this, the % operator in Go is technically a remainder operator, not a strict mathematical modulo operator. The behavior of % is formally defined by the following equation: (a / b) * b + (a % b) == a A critical characteristic of Go’s remainder operator is that the sign of the result always matches the sign of the dividend (the left operand). The sign of the divisor (the right operand) has no effect on the sign of the result.
package main

import "fmt"

func main() {
    // Positive dividend: result is always positive
    fmt.Println(5 % 3)   // Output: 2
    fmt.Println(5 % -3)  // Output: 2

    // Negative dividend: result is always negative
    fmt.Println(-5 % 3)  // Output: -2
    fmt.Println(-5 % -3) // Output: -2
}

Zero-Evaluation Rules

The % operator is subject to strict zero-evaluation rules for the right operand (the divisor). Go distinguishes between constant and non-constant divisors:
  1. Compile-Time Error: If the divisor is a constant 0, the compiler catches the error during compilation.
  2. Runtime Panic: If the divisor is a variable that evaluates to 0 at runtime, the operation triggers a panic.
package main

func main() {
    // Compile-time error:
    // invalid operation: 10 % 0 (division by zero)
    // _ = 10 % 0 

    a := 10
    b := 0
    
    // Compiles successfully, but triggers a runtime panic:
    // panic: runtime error: integer divide by zero
    _ = a % b 
}
Master Go with Deep Grasping Methodology!Learn More