Page Content

Tutorials

Essential Operators In GoLang Every Programmer Should Know

Operators in GoLang

Operators in Go programming are functions or symbols that tell the compiler how to carry out particular logical, mathematical, or other operations. Go has a wide variety of built-in operators that may be divided into different categories.

Here is a description of Go’s fundamental operators along with sample code:

Arithmetic Operators

Arithmetic operators carry out computations in mathematics. The standard arithmetic operators that Go supports are as follows:

+ (Addition): Adds two operands.

– (Subtraction): Subtracts the second operand from the first.

* (Multiplication): Multiplies both operands.

/ (Division): The numerator is divided by the denominator. It carries out floor division on integers, returning the greatest number that is less than or equal to the quotient. Explicitly converting the data to a floating-point type (such as float64()) prior to division will get a float result from integer division.

% (Remainder/Modulus): After dividing an integer, it returns the residual. This is helpful for figuring out whether a number is odd or even (i.e., i % 2 == 0). When dealing with floating-point numbers, math can be used.Mod from the package for maths.

Additionally, Go offers unique operators for incrementing and decrementing:

++ (Increment operator): Gives an integer number a one-fold increase. ++count and other prefix increments are not supported by Go.

— (Decrement operator): Subtracts one from an integer value.

Unary Arithmetic Operations: It is also possible to employ the + and – signs as unary operators with a single value to change its sign (-x) or return its identity (+x).

Type Compatibility: Only data types of the same kind can be utilised with operators. Compiler errors occur when an operation is attempted on different data types, such as adding an int and a float64 or concatenating strings and integers.

Example:

package main
import "fmt"
import "math" // For math.Mod
func main() {
    var a int = 21
    var b int = 10
    var c int
    
    // Addition
    c = a + b
    fmt.Printf("Line 1 - Value of c is %d\n", c) 
    
    // Subtraction
    c = a - b
    fmt.Printf("Line 2 - Value of c is %d\n", c)
    
    // Multiplication
    c = a * b
    fmt.Printf("Line 3 - Value of c is %d\n", c)
    
    // Division (integer)
    c = a / b
    fmt.Printf("Line 4 - Value of c is %d\n", c) 
    
    // Modulus
    c = a % b
    fmt.Printf("Line 5 - Value of c is %d\n", c) 
    
    // Increment
    a++
    fmt.Printf("Line 6 - Value of a is %d\n", a) 
    
    // Decrement
    a--
    fmt.Printf("Line 7 - Value of a is %d\n", a) 
    // Floating-point division and modulus
    s := 80.0
    t := 6.0
    r := s / t
    fmt.Printf("Float division: %.2f\n", r) 
    q := 36.0
    w := 8.0
    modResult := math.Mod(q, w)
    fmt.Printf("Float modulus: %.2f\n", modResult) 
}

Output

Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2
Line 5 - Value of c is 1
Line 6 - Value of a is 22
Line 7 - Value of a is 21
Float division: 13.33
Float modulus: 4.00

Relational (Comparison) Operators

To compare values and evaluate to a single Boolean value (true or false), comparison operators are utilized.

OperatorDescriptionExample (A=10, B=20)
==Checks if values are equal.(A == B) is false.
!=Checks if values are not equal.(A != B) is true.
<Checks if the left operand is less than the right.(A < B) is true.
>Checks if the left operand is greater than the right.(A > B) is false.
<=Checks if the left operand is less than or equal to the right.(A <= B) is true.
>=Checks if the left operand is greater than or equal to the right.(A >= B) is false.

String Comparison: These operators can also be used for string comparisons. Unless you use a special string technique (like strings), they are case-sensitive.equalFold(). Go uses the ASCII character values to perform lexicographic string comparisons.

Distinction: Making the distinction between = (the assignment operator) and == (the comparison operator) is essential. In the event that you inadvertently use = when == is intended, Go reports an error.

Example:

package main
import "fmt"
func main() {
    var x int = 5
    var y int = 8
    
    fmt.Println("x == y:", x == y) 
    fmt.Println("x != y:", x != y)  
    fmt.Println("x < y:", x < y)    
    fmt.Println("x > y:", x > y)    
    fmt.Println("x <= y:", x <= y) 
    fmt.Println("x >= y:", x >= y) 
    // String comparison
    s1 := "Sammy"
    s2 := "sammy"
    fmt.Println("Sammy == sammy:", s1 == s2) 
    
    s3 := "Sammy"
    fmt.Println("Sammy == Sammy:", s1 == s3) 
}

Output

x == y: false
x != y: true
x < y: true
x > y: false
x <= y: true
x >= y: false
Sammy == sammy: false
Sammy == Sammy: true

Logical Operators

Combining or altering Boolean statements with logical operators yields a single Boolean value.

  • && (Logical AND): True if both operands are true.
  • || (Logical OR): True if at least one operand is true.
  • ! (Logical NOT): Reverses the logical state of its operand; if true, it makes it false, and vice versa.

Truth Tables: These tables describe the operation of logical operators:

ExpressionValue
true && truetrue
true && falsefalse
false && truefalse
false && falsefalse
ExpressionValue
`true
`true
`false
`false
ExpressionValue
!truefalse
!falsetrue

Short-circuit Logic: Go employs short-circuit reasoning. If the first condition is not true for &&, the second condition is not assessed. The second condition is not tested for || if the first condition is true.

Example:

package main
import "fmt"
func main() {
    // && (AND)
    fmt.Println(true && true)   
    fmt.Println(true && false) 
    
    // || (OR)
    fmt.Println(true || true)   
    fmt.Println(true || false)
    
    // ! (NOT)
    fmt.Println(!true)          
    fmt.Println(!(false && false))
}

Output

true
false
true
true
false
true

Assignment Operators

Values are assigned to variables using assignment operators.

= (Simple assignment operator): The variable on the left is given the value on the right. When at least one new variable is on the left side, it can be used with var for declaration and assignment or.

Compound Assignment Operators: By combining the = operator with an arithmetic operator, these manipulate the value of a variable and then return the outcome to it.

OperatorExampleEquivalent to
+=C += AC = C + A
-=C -= AC = C - A
*=C *= AC = C * A
/=C /= AC = C / A
%=C %= AC = C % A
<<=C <<= 2C = C << 2
>>=C >>= 2C = C >> 2
&=C &= 2C = C & 2
^=C ^= 2C = C ^ 2
`=``C

Example:

package main
import "fmt"
func main() {
    var w int = 5
    w += 1 // w is now 6
    fmt.Println(w) 
    // Using compound assignment in a loop
    values := []int{0, 1, 2, 3}
    for _, x := range values {
        currentValue := x
        currentValue *= 2 // Multiply by 2 and assign back
        fmt.Println(currentValue)
    }
    
}

Output

6
0
2
4
6

Miscellaneous Operators

& (Address of operator): Gives back the variable’s memory address.

* (Dereference operator): Utilized in conjunction with pointer variables to change or access the value that the pointer points to.

%T (Format verb): Used in conjunction with fmt.Printf to print a variable’s data type.

Operator Precedence

How an expression is evaluated and how its terms are grouped depends on operator precedence. First, operators with a greater precedence are assessed. Multiplication, for example, is given precedence over addition. The sequence of assessment can be explicitly controlled, as in mathematics, by using brackets ().

Example:

package main
import "fmt"
func main() {
    var u int
    u = 10 + 10 * 5 // Multiplication (10 * 5 = 50) is done first, then addition (10 + 50 = 60)
    fmt.Println(u)  
    u = (10 + 10) * 5 // Parentheses ensure addition (10 + 10 = 20) is done first, then multiplication (20 * 5 = 100)
    fmt.Println(u) 
}

Output

60
100

You can also read What Is Mean By Loops In Go Language With Code Examples

Agarapu Geetha
Agarapu Geetha
My name is Agarapu Geetha, a B.Com graduate with a strong passion for technology and innovation. I work as a content writer at Govindhtech, where I dedicate myself to exploring and publishing the latest updates in the world of tech.
Index