Home Go Tutorial on Operators in Go

Tutorial on Operators in Go

Operators in Go allow you to perform computations, comparisons, and logical operations on variables and constants.

Go provides a range of operators that fall into several categories, including arithmetic, relational, logical, bitwise, and assignment operators.

In this tutorial, we’ll cover:

1. Arithmetic Operators

Arithmetic operators are used for mathematical calculations, such as addition, subtraction, multiplication, and division.

Operator Description Example
+ Addition a + b
Subtraction a – b
* Multiplication a * b
/ Division a / b
% Modulus (remainder) a % b
package main

import "fmt"

func main() {
    a, b := 10, 3

    fmt.Println("Addition:", a+b)         // 10 + 3 = 13
    fmt.Println("Subtraction:", a-b)      // 10 - 3 = 7
    fmt.Println("Multiplication:", a*b)   // 10 * 3 = 30
    fmt.Println("Division:", a/b)         // 10 / 3 = 3 (integer division)
    fmt.Println("Modulus:", a%b)          // 10 % 3 = 1
}

Output:

Addition: 13
Subtraction: 7
Multiplication: 30
Division: 3
Modulus: 1

Note: Go performs integer division if both operands are integers, discarding any remainder.

2. Relational Operators

Relational operators are used to compare two values and return a boolean result (true or false).

Operator Description Example
== Equal to a == b
!= Not equal to a != b
> Greater than a > b
< Less than a < b
>= Greater than or equal to a >= b
<= Less than or equal to a <= b
package main

import "fmt"

func main() {
    a, b := 5, 10

    fmt.Println("Equal to:", a == b)               // false
    fmt.Println("Not equal to:", a != b)           // true
    fmt.Println("Greater than:", a > b)            // false
    fmt.Println("Less than:", a < b)               // true
    fmt.Println("Greater than or equal to:", a >= b) // false
    fmt.Println("Less than or equal to:", a <= b)     // true
}

Output:

Equal to: false
Not equal to: true
Greater than: false
Less than: true
Greater than or equal to: false
Less than or equal to: true

3. Logical Operators

Logical operators are used to combine multiple boolean expressions or values and return a boolean result.

Operator Description Example
&& Logical AND a && b
` `
! Logical NOT !a
package main

import "fmt"

func main() {
    x, y := true, false

    fmt.Println("Logical AND:", x && y) // false
    fmt.Println("Logical OR:", x || y)  // true
    fmt.Println("Logical NOT:", !x)     // false
}

Output:

Logical AND: false
Logical OR: true
Logical NOT: false

4. Bitwise Operators

Bitwise operators operate on bits of integer values. These operators are used for low-level programming, such as working with binary data.

Operator Description Example
& Bitwise AND a & b
` ` Bitwise OR
^ Bitwise XOR a ^ b
&^ Bitwise AND NOT a &^ b
<< Left shift a << b
>> Right shift a >> b
package main

import "fmt"

func main() {
    a, b := 5, 3 // a = 0101, b = 0011 in binary

    fmt.Println("Bitwise AND:", a&b)   // 0101 & 0011 = 0001 (1)
    fmt.Println("Bitwise OR:", a|b)    // 0101 | 0011 = 0111 (7)
    fmt.Println("Bitwise XOR:", a^b)   // 0101 ^ 0011 = 0110 (6)
    fmt.Println("Bitwise AND NOT:", a&^b) // 0101 &^ 0011 = 0100 (4)
    fmt.Println("Left shift:", a<<1)   // 0101 << 1 = 1010 (10)
    fmt.Println("Right shift:", a>>1)  // 0101 >> 1 = 0010 (2)
}

Output:

Bitwise AND: 1
Bitwise OR: 7
Bitwise XOR: 6
Bitwise AND NOT: 4
Left shift: 10
Right shift: 2

5. Assignment Operators

Assignment operators are used to assign values to variables. Some operators combine assignment with other operations.

Operator Description Example
= Assign a = b
+= Add and assign a += b
-= Subtract and assign a -= b
*= Multiply and assign a *= b
/= Divide and assign a /= b
%= Modulus and assign a %= b
&= Bitwise AND and assign a &= b
` =` Bitwise OR and assign
^= Bitwise XOR and assign a ^= b
<<= Left shift and assign a <<= b
>>= Right shift and assign a >>= b
package main

import "fmt"

func main() {
    x := 10

    x += 5  // x = x + 5
    fmt.Println("After += 5:", x) // 15

    x *= 2  // x = x * 2
    fmt.Println("After *= 2:", x) // 30

    x -= 10 // x = x - 10
    fmt.Println("After -= 10:", x) // 20

    x /= 4  // x = x / 4
    fmt.Println("After /= 4:", x) // 5

    x %= 3  // x = x % 3
    fmt.Println("After %= 3:", x) // 2
}

Output:

After += 5: 15
After *= 2: 30
After -= 10: 20
After /= 4: 5
After %= 3: 2

6. Miscellaneous Operators

The & and * Operators (Pointer Operators)

  • &: Returns the memory address of a variable (pointer).
  • *: Dereferences a pointer, accessing the value at the memory address.
package main

import "fmt"

func main() {
    a := 42
    p := &a        // Pointer to a
    fmt.Println("Address of a:", p)
    fmt.Println("Value of a via pointer:", *p)
}

Output:

Address of a: (memory address)
Value of a via pointer: 42

In this example:

  • &a gives the memory address of a.
  • *p accesses the value at the memory address held by p.

Examples and Best Practices

a) Use Appropriate Operators for Logical Flow

Logical operators (&&, ||, !) are useful in conditional statements to combine multiple conditions.

package main

import "fmt"

func main() {
    age := 25
    isMember := true

    if age >= 18 && isMember {
        fmt.Println("Eligible for discount")
    } else {
        fmt.Println("Not eligible for discount")
   

 }
}

b) Use Short Assignment Operators for Cleaner Code

If you’re updating a variable’s value based on its existing value, use short assignment operators like +=, *=, etc., to make your code more readable.

package main

import "fmt"

func main() {
    counter := 1
    counter += 10 // Increment by 10
    fmt.Println("Counter:", counter)
}

c) Be Mindful of Integer Division

In Go, dividing two integers results in an integer, discarding the remainder. Use floating-point numbers for precise division results.

package main

import "fmt"

func main() {
    a, b := 5, 2
    result := float64(a) / float64(b) // Convert to float64 for precise division
    fmt.Println("Division result:", result)
}

Output:

Division result: 2.5

Summary

In this tutorial, we covered the main operators in Go:

  1. Arithmetic Operators: For performing mathematical calculations.
  2. Relational Operators: For comparing values.
  3. Logical Operators: For combining boolean expressions.
  4. Bitwise Operators: For low-level bit manipulation.
  5. Assignment Operators: For assigning and updating values.
  6. Miscellaneous Operators: Pointers for accessing memory addresses.

Understanding operators is essential in Go, as they allow you to perform calculations, comparisons, and logical operations on data efficiently. By mastering these operators and using them appropriately, you can write cleaner, more efficient Go code.

 

You may also like