Go:Go Operators: Arithmetic, Comparison, and Bitwise Logic
Go•Operators

Go Operators: Arithmetic, Comparison, and Bitwise Logic

Learn Go operator precedence, integer truncation, and bitwise operations.

Syntax

sum := a + b isValid := x > 0 && y < 10

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
&&, ||Logical OperatorsShort-circuit boolean logic.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Go locally:

package main

import "fmt"

func main() {
    a := 26
    b := 4

    fmt.Printf("Addition:    %d + %d = %d\n", a, b, a+b)
    fmt.Printf("Integer Div: %d / %d = %d (truncated)\n", a, b, a/b)
    fmt.Printf("Float Div:   %.2f\n", float64(a)/float64(b))
    fmt.Printf("Remainder:   %d %% %d = %d\n", a, b, a%b)

    // Bitwise shift
    flags := 1 << 3 // 2^3 = 8
    fmt.Printf("Bitwise 1<<3: %d\n", flags)
}
Expected Output:
Addition:    26 + 4 = 30
Integer Div: 26 / 4 = 6 (truncated)
Float Div:   6.50
Remainder:   26 % 4 = 2
Bitwise 1<<3: 8

How It Works: Step-by-Step

  • Lines 10-12: Shows integer division truncation and explicit float64 casting.
  • Line 15: Performs bitwise left shift.

Key Concepts

  • In Go, operations between mismatched types (int + float64) are prohibited without explicit casting.
  • Integer division truncates decimals toward zero.

Common Mistake: Mixing different numeric types without explicit conversion

Go does not perform implicit numeric conversions. You must cast types explicitly.

❌ Incorrect
var i int = 10; var f float64 = 2.5; var res = i * f; // Compile Error: mismatched types!
✅ Correct
var res = float64(i) * f;

Related Go Tutorials & Compiler

Run and test Go on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Go Online Compiler