Arithmetic with Constants
Basic Arithmetic Operations
Golang allows performing arithmetic operations with constants at compile-time. These operations include addition, subtraction, multiplication, division, and modulus.
package main
import "fmt"
func main() {
const a = 10
const b = 5
const sum = a + b // Addition
const difference = a - b // Subtraction
const product = a * b // Multiplication
const quotient = a / b // Division
const remainder = a % b // Modulus
fmt.Println(sum, difference, product, quotient, remainder)
}
Constant Type Inference
graph TD
A[Constant Arithmetic] --> B[Untyped Constants]
A --> C[Type Preservation]
A --> D[Compile-Time Evaluation]
Golang provides powerful type inference during constant arithmetic:
Operation Type |
Behavior |
Example |
Untyped Constants |
Flexible type conversion |
const x = 5 + 3.14 |
Typed Constants |
Strict type matching |
const int a = 5; const int b = 3 |
Mixed Types |
Automatic type promotion |
const result = 10 * 3.5 |
Complex Constant Calculations
package main
import "fmt"
func main() {
// Complex constant calculations
const (
Pi = 3.14159
Radius = 5
Circumference = 2 * Pi * Radius
Area = Pi * Radius * Radius
)
fmt.Printf("Circumference: %.2f\n", Circumference)
fmt.Printf("Area: %.2f\n", Area)
}
Compile-Time Constant Expressions
package main
import "fmt"
func main() {
// Nested constant calculations
const (
BaseValue = 10
Multiplier = 2
ComplexCalc = BaseValue * (Multiplier + 3)
)
fmt.Println("Complex Calculation:", ComplexCalc)
}
Advanced Constant Arithmetic
package main
import "fmt"
func main() {
// Bitwise operations with constants
const (
Flag1 = 1 << 0 // 1
Flag2 = 1 << 1 // 2
Flag3 = 1 << 2 // 4
CombinedFlags = Flag1 | Flag2
)
fmt.Printf("Combined Flags: %d\n", CombinedFlags)
}
Limitations and Considerations
- Constant arithmetic is evaluated at compile-time
- Cannot perform runtime modifications
- Limited to compile-time computable expressions
By mastering constant arithmetic, developers can write more efficient and predictable code with LabEx's programming techniques.