How to use operators in go lang!

In this tutorial, we discuss operators in go, How many operators and what kind of operator go does support.

What is Operator?

An operator is a special symbol that indicates a certain task is carried out. Operators in programming language most of the time have the same meaning as what we do in mathematics. Every expression contains operator and operand, operand are the input data to that expression on which these operators are getting applied.

Expressions are fabricated from operands and operators. The operators of an expression indicate which operations to apply to the operands. The order of execution in expression is decided by the precedence and associativity of the operators.

Operators are generally classified into two sections unary and binary. The operators work on one single operand known as unary where the operator who needs two or more operand known as a binary operator.

Precedence    Operator
    5             *  /  %  <<  >>  &  &^
    4             +  -  |  ^
    3             ==  !=  <  <=  >  >=
    2             &&
    1             ||

Sign Operators in go:

// sing operatos in go language
func singOperaor(){
    fmt.Println(4)
    fmt.Println(+4)
    fmt.Println(-4)

      var i = 1

    fmt.Println(-i)
    fmt.Println(-(-i))
}

As you could see in the above example the default sign indicates is positive, even though you intentionally mention positive(+) and negative(-).

$ go run operators.go 
4
4
-4
-1
1

The above is the unary operator because these needs only one operand for processing.

Assignment Operator in GO:

Assignment operator are the operator does assigns the right hand value to left hand side variable. As we discussed in the last couple of article about variables, variables are the placeholder of value. The assignment operator has different meaning in mathematics. Assignment operator also known as equality operator ” = “. This operator indicates that the both left and right side are equal.

var i = 5

Above we assigned value 5 to variable i. or i is a placeholder to hold the value 5. A reverse assignment is not possible in programming this leads to a syntax error 5=i.

i = i + 5

The above expression indicates we are adding 5 value to existing value in 5, as we have assigned value 5+5 now i holds 10.

Go also support short variable declaration operator. This operator:=, declares a variable and assigns a value in one single step. The i := 7 is equal to var i = 7.

Increment and Decrement operators:

We often increment and decrement certain value while in loop or conditional expression. Go lang also support this operator ++ and –.

If you are already familiar with any programming language then you may know the importance of this increment and decrement operator.

func assignIncDcr(){
  
    i := 4
    //increment by one i=i+1
    i++
    i++

    fmt.Println(i)
    // decrement by one i=i-1
    i--
    fmt.Println(i)
}

Output:

$ go run operators.go 
6
5

Compound assignment operators:

The compound assignment operators are binary operator because they act on two operand. This is the shorthand assignment operator. This operators also plays key role in looping and in conditional decisions.

y = y + 5
// compound assignment operator
y += 5

The compound assignment gives the same output as the above expression but it gives a shorthand format of the above operation. GO support all arithmetic operators as shorthand operator.

Other compound operator:

-=   *=   /=   %=   &=   |=   <<=   >>=
func compoundOperator(){

    var y int = 2
    // addition
    y = y + 2

    fmt.Println(y)
    // addition using comound
    y += 3
    fmt.Println(y)
    // multiplication using compound
    y *= 7
    fmt.Println(y)
}

Output:

$ go run operators.go 
4
7
49

var y int = 2
// addition
y = y + 2

here we have created the y variable and assigned value 2 to it and then y=y+2 so y=4 value. y += 3 now this expression is the same as y=y+3.

y *= 7

The above expression is same like y=y*7 and it gives output as 49.

Arithmetic operators in go:

Below are the arithmetic operators supported by go.

Operator                    DataTypes
+    sum                    integers, floats, complex values, strings
-    difference             integers, floats, complex values
*    product                integers, floats, complex values
/    quotient               integers, floats, complex values
%    remainder              integers

Following code snippet demonstrate the arithmetic operations.

package main

import "fmt"

func main(){

	var y = 6
    var x = 7
    var z = 8

    var add = y + x + z
    var sb = z - y
    var mult = y * x
    var div = z / 3
    var rem = z % y

    fmt.Println(add)
    fmt.Println(sb)
    fmt.Println(mult)
    fmt.Println(div)
    fmt.Println(rem)
}

Output:

$ go run arithematcisop.go 
21
2
42
2
2

The all above arithmetic operator has precedence and meaning same as in mathematics.

The modulo operator(%) or reminder operator does divide the number and find the remainder.

In the division, when in the division both the operand value is integer then output is also integer value.

y = 7 / 2

fmt.Println(y)

the above code snippet output is 3 not 3.5.

Where as if we have any of the value is float then output in floating point.

y = 7 / 2.0

fmt.Println(y)

Output is 3.5 value.

Comparison Operator in go:

Operators DataTypes

<    less than              integers
<=   less than equal to     integers
>    greater than           integers
>=   greater than equal to  integers
==   equal to equal         integers 
!=   not equal to           integers 
Let us take basic example.
package main

import "fmt"

func main(){

	var x = 3
    var y = 8

    fmt.Println(x == y)
    fmt.Println(y > x)

    if y > x {

        fmt.Println("y is greater than x")
    }
}

Output:

$ go run booleanop.go 
false
true
y is greater than x
if y > x {

    fmt.Println("y is greater than x")
}

Comparison operator always return the result in boolean value.

Logical Operators in go:

List of logical operators supported by go.

OperatorsName
&&logical and
||logical or
!negation

List of logical operators supported by go.
The above relational operators result value is always boolean either true or false. Logical operators tables are working like in below fashion.

Boolean Logical Operators In Java with example program

Code Snippet.

func logicalAnd(){
	var a = true && true
    var b = true && false
    var c = false && true
    var d = false && false

    fmt.Println(a)
    fmt.Println(b)
    fmt.Println(c)
    fmt.Println(d)
}

Output:

$ go run booleanop.go 
true
false
false
false

Logical OR operator.

func logicalOR(){

	var a = true || true
    var b = true || false
    var c = false || true
    var d = false || false

    fmt.Println(a)
    fmt.Println(b)
    fmt.Println(c)
    fmt.Println(d)
}

Complete Code:

package main

import "fmt"

func logicalAnd(){
	var a = true && true
    var b = true && false
    var c = false && true
    var d = false && false

    fmt.Println(a)
    fmt.Println(b)
    fmt.Println(c)
    fmt.Println(d)
}

func logicalOR(){

	var a = true || true
    var b = true || false
    var c = false || true
    var d = false || false

    fmt.Println(a)
    fmt.Println(b)
    fmt.Println(c)
    fmt.Println(d)
}

func logicalNot(){
	fmt.Println(!true)
    fmt.Println(!false)
    fmt.Println(!(4 < 3))
}
//comparision operators
func gtlt(){
	var x = 3
    var y = 8
    // equality check 
	fmt.Println(x == y)
	// greater than operator 
    fmt.Println(y > x)

    if y > x {

        fmt.Println("y is greater than x")
    }
}

func main(){

	gtlt()
	fmt.Println()
	fmt.Println("Logical AND")
	logicalAnd()
	fmt.Println()
	fmt.Println("Logical OR ")
	logicalOR()
	fmt.Println()
	fmt.Println("Logical NOT")
	logicalNot()
	fmt.Println()
}

Output:

$ go run booleanop.go
false
true
y is greater than x

Logical AND
true
false
false
false

Logical OR
true
true
true
false

Logical NOT
false
true
true

Bitwise Operator in go:

Binary numbers are native to computers. Binary, octal, decimal, or hexadecimal symbols are only notations of the same number. Bitwise operators work with bits of a binary number.

&    bitwise AND            integers
|    bitwise OR             integers
^    bitwise XOR            integers
&^   bit clear (AND NOT)    integers

<<   left shift             integer << unsigned integer
>>   right shift            integer >> unsigned integer

The bitwise and operator performs bit-by-bit comparison between two numbers. The result for a bit position is 1 only if both corresponding bits in the operands are 1.

      00110
   &  00011
   =  00010

The first number is a binary notation of 6, the second is 3, and the result is 2.

fmt.Println(6 & 3) 
fmt.Println(3 & 6) 

Python Bitwise Operators - Start operating on the bits of numbers -  TechVidvan

Channel operator in go!

A channel operator is also known as receiver operator. The value of the receive operation <-ch is the value received from the channel ch.

A channel is a typed pipe through which we can send and receive values with the channel operator '<- ‘.

This example shows the channel operator

go func() { messages <- “hello” }()

Code snippet

package main 

import "fmt"

func main(){

    text := make(chan string)

    go func() { text <- "channel received" }()

    msg := <-text
    fmt.Println(msg)

}

Output:

$ go run channelop.go 
channel received

If the type starts with the operator * or <-, or if the type starts with the keyword func and has no result list, it must be parenthesized when necessary to avoid ambiguity

*Point(p)        // same as *(Point(p))

(*Point)(p)      // p is converted to *Point

<-chan int(c)    // same as <-(chan int(c))

(<-chan int)(c)  // c is converted to <-chan int

func()(x)        // function signature func() x

(func())(x)      // x is converted to func()

(func() int)(x)  // x is converted to func() int

func() int(x)    // x is converted to func() int (unambiguous)

Conclusion:

This article is all about the operators supported by go language, we demonstrated logical, arithmetic, comparison, and channel operator.