Go Tutorial

Go exercises, go assignment operators, assignment operators.

Assignment operators are used to assign values to variables.

In the example below, we use the assignment operator ( = ) to assign the value 10 to a variable called x :

The addition assignment operator ( += ) adds a value to a variable:

A list of all assignment operators:

Get Certified

COLOR PICKER

colorpicker

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

[email protected]

Top Tutorials

Top references, top examples, get certified.

Popular Tutorials

Popular examples, learn python interactively, go introduction.

  • Golang Getting Started
  • Go Variables
  • Go Data Types
  • Go Print Statement
  • Go Take Input
  • Go Comments

Go Operators

  • Go Type Casting

Go Flow Control

  • Go Boolean Expression
  • Go if...else
  • Go for Loop
  • Go while Loop
  • Go break and continue

Go Data Structures

  • Go Functions
  • Go Variable Scope
  • Go Recursion
  • Go Anonymous Function
  • Go Packages

Go Pointers & Interface

Go Pointers

  • Go Pointers and Functions
  • Go Pointers to Struct
  • Go Interface
  • Go Empty Interface
  • Go Type Assertions

Go Additional Topics

Go defer, panic, and recover

Go Tutorials

Go Booleans (Relational and Logical Operators)

  • Go Pointers to Structs

In Computer Programming, an operator is a symbol that performs operations on a value or a variable.

For example, + is an operator that is used to add two numbers.

Go programming provides wide range of operators that are categorized into following major categories:

  • Arithmetic operators
  • Assignment operator
  • Relational operators
  • Logical operators
  • Arithmetic Operator

We use arithmetic operators to perform arithmetic operations like addition, subtraction, multiplication, and division.

Here's a list of various arithmetic operators available in Go.

Example 1: Addition, Subtraction and Multiplication Operators

Example 2: golang division operator.

In the above example, we have used the / operator to divide two numbers: 11 and 4 . Here, we get the output 2 .

However, in normal calculation, 11 / 4 gives 2.75 . This is because when we use the / operator with integer values, we get the quotients instead of the actual result.

The division operator with integer values returns the quotient.

If we want the actual result we should always use the / operator with floating point numbers. For example,

Here, we get the actual result after division.

Example 3: Modulus Operator in Go

In the above example, we have used the modulo operator with numbers: 11 and 4 . Here, we get the result 3 .

This is because in programming, the modulo operator always returns the remainder after division.

The modulo operator in golang returns the remainder after division.

Note: The modulo operator is always used with integer values.

  • Increment and Decrement Operator in Go

In Golang, we use ++ (increment) and -- (decrement) operators to increase and decrease the value of a variable by 1 respectively. For example,

In the above example,

  • num++ - increases the value of num by 1 , from 5 to 6
  • num-- - decreases the value of num by 1 , from 5 to 4

Note: We have used ++ and -- as prefixes (before variable). However, we can also use them as postfixes ( num++ and num-- ).

There is a slight difference between using increment and decrement operators as prefixes and postfixes. To learn the difference, visit Increment and Decrement Operator as Prefix and Postfix .

  • Go Assignment Operators

We use the assignment operator to assign values to a variable. For example,

Here, the = operator assigns the value on right ( 34 ) to the variable on left ( number ).

Example: Assignment Operator in Go

In the above example, we have used the assignment operator to assign the value of the num variable to the result variable.

  • Compound Assignment Operators

In Go, we can also use an assignment operator together with an arithmetic operator. For example,

Here, += is additional assignment operator. It first adds 6 to the value of number ( 2 ) and assigns the final result ( 8 ) to number .

Here's a list of various compound assignment operators available in Golang.

  • Relational Operators in Golang

We use the relational operators to compare two values or variables. For example,

Here, == is a relational operator that checks if 5 is equal to 6 .

A relational operator returns

  • true if the comparison between two values is correct
  • false if the comparison is wrong

Here's a list of various relational operators available in Go:

To learn more, visit Go relational operators .

  • Logical Operators in Go

We use the logical operators to perform logical operations. A logical operator returns either true or false depending upon the conditions.

To learn more, visit Go logical operators .

More on Go Operators

The right shift operator shifts all bits towards the right by a certain number of specified bits.

Suppose we want to right shift a number 212 by some bits then,

For example,

The left shift operator shifts all bits towards the left by a certain number of specified bits. The bit positions that have been vacated by the left shift operator are filled with 0 .

Suppose we want to left shift a number 212 by some bits then,

In Go, & is the address operator that is used for pointers. It holds the memory address of a variable. For example,

Here, we have used the * operator to declare the pointer variable. To learn more, visit Go Pointers .

In Go, * is the dereferencing operator used to declare a pointer variable. A pointer variable stores the memory address. For example,

In Go, we use the concept called operator precedence which determines which operator is executed first if multiple operators are used together. For example,

Here, the / operator is executed first followed by the * operator. The + and - operators are respectively executed at last.

This is because operators with the higher precedence are executed first and operators with lower precedence are executed last.

Table of Contents

  • Introduction
  • Example: Addition, Subtraction and Multiplication
  • Golang Division Operator

Sorry about that.

Related Tutorials

Programming

MarketSplash

Golang := Vs = Exploring Assignment Operators In Go

Explore the nuances of Go's := and = operators. This article breaks down their uses, scope considerations, and best practices, helping you write clearer, more efficient Go code.

In Go, understanding the distinction between the ':=' and '=' operators is crucial for efficient coding. The ':=' operator is used for declaring and initializing a new variable, while '=' is for assigning a value to an existing variable. This nuanced difference can significantly impact the functionality and efficiency of your Go programs.

golang operators in assignment

Understanding := (Short Variable Declaration)

Understanding = (assignment operator), when to use := vs =, scope considerations, type inference with :=, common pitfalls and how to avoid them, best practices, frequently asked questions.

Short variable declaration , designated by := , is a concise way to declare and initialize a variable in Go. This operator allows you to create a variable with a type inferred from the right-hand side of the expression.

For instance, consider the following code snippet:

Here, name and age are declared and initialized without explicitly stating their types ( string and int , respectively).

When To Use Short Variable Declaration

Limitations and scope.

The := operator is particularly useful in local scopes , such as within functions or blocks, where brevity and efficiency are key. It's a go-to choice for assigning initial values to variables that will be used within a limited scope .

Consider a function:

count is declared and initialized within the function's scope, making the code cleaner and more readable.

While := is convenient, it has limitations. It cannot be used for global variable declarations. Also, it's designed for declaring new variables . If you try to redeclare an already declared variable in the same scope using := , the compiler will throw an error.

For example:

In summary, := is a powerful feature in Go for efficient variable declaration and initialization, with a focus on type inference and local scope usage. Use it to write cleaner, more concise code in functions and blocks.

The assignment operator , = , in Go, is used to assign values to already declared variables. Unlike := , it does not declare a new variable but modifies the value of an existing one.

Here, age is first declared as an integer, and then 30 is assigned to it using = .

Reassignment And Existing Variables

Global and local scope.

One of the key uses of = is to reassign values to variables. This is crucial in scenarios where the value of a variable changes over time within the same scope.

In this case, count is initially 10, but is later changed to 20.

The = operator works in both global and local scopes . It is versatile and can be used anywhere in your code, provided the variable it's being assigned to has been declared.

In this snippet, globalVar is assigned a value within a function, while localVar is assigned within its local scope.

Remember, = does not infer type. The variable's type must be clear either from its declaration or context. This operator is essential for variable value management throughout your Go programs, offering flexibility in variable usage and value updates.

Understanding the Problem:

Here is the relevant code snippet:

Here's the modified code:

Choosing between := and = in Go depends on the context and the specific requirements of the code. It's crucial to understand their appropriate use cases to write efficient and error-free programs.

New Variable Declaration

Existing variable assignment, reassigning and declaring variables.

Use := when you need to declare and initialize a new variable within a local scope. This operator is a shorthand that infers the variable's type based on the value assigned.

In this example, name is a new variable declared and initialized within the function.

Use = when you are working with already declared variables . This operator is used to update or change the value of the variable.

Here, count is an existing variable, and its value is being updated.

:= is limited to local scopes , such as inside functions or blocks. It cannot be used for global variable declarations. Conversely, = can be used in both local and global scopes.

It's important to distinguish situations where you are reassigning a value to an existing variable and when you are declaring a new one. Misusing := and = can lead to compile-time errors.

In summary, := is for declaring new variables with type inference, primarily in local scopes, while = is for assigning or updating values in both local and global scopes. Proper usage of these operators is key to writing clean and efficient Go code.

Understanding the scope of variables in Go is critical when deciding between := and = . The scope determines where a variable can be accessed or modified within the program.

Local Scope And :=

Global scope and =, redeclaration and shadowing, choosing the right scope.

The := operator is restricted to local scope . It's typically used within functions or blocks to declare and initialize variables that are not needed outside of that specific context.

Here, localVariable is accessible only within the example function.

Variables declared outside of any function, in the global scope , can be accessed and modified using the = operator from anywhere in the program.

globalVariable can be accessed and modified in any function.

In Go, shadowing can occur if a local variable is declared with the same name as a global variable. This is a common issue when using := in a local scope.

In the function example , num is a new local variable, different from the global num .

It's important to choose the right scope for your variables. Use global variables sparingly, as they can lead to code that is harder to debug and maintain. Prefer local scope with := for variables that don't need to be accessed globally.

Understanding and managing scope effectively ensures that your Go programs are more maintainable, less prone to errors, and easier to understand. Proper scope management using := and = is a key aspect of effective Go programming.

Type inference is a powerful feature of Go's := operator. It allows the compiler to automatically determine the type of the variable based on the value assigned to it.

Automatic Type Deduction

Mixed type declarations, limitations of type inference, practical use in functions.

When you use := , you do not need to explicitly declare the data type of the variable. This makes the code more concise and easier to write, especially in complex functions or when dealing with multiple variables.

In these examples, the types ( string for name and int for age ) are inferred automatically.

Type inference with := also works when declaring multiple variables in a single line, each possibly having a different type.

Here, name and age are declared in one line with different inferred types.

While type inference is convenient, it is important to be aware of its limitations . The type is inferred at the time of declaration and cannot be changed later.

In this case, attempting to assign a string to balance , initially inferred as float64 , results in an error.

Type inference is particularly useful in functions, especially when dealing with return values of different types or working with complex data structures.

Here, value 's type is inferred from the return type of someCalculation .

Type inference with := simplifies variable declaration and makes Go code more readable and easier to maintain. It's a feature that, when used appropriately, can greatly enhance the efficiency of your coding process in Go.

When using := and = , there are several common pitfalls that Go programmers may encounter. Being aware of these and knowing how to avoid them is crucial for writing effective code.

Re-declaration In The Same Scope

Shadowing global variables, incorrect type inference, accidental global declarations, using = without prior declaration.

One common mistake is attempting to re-declare a variable in the same scope using := . This results in a compilation error.

To avoid this, use = for reassignment within the same scope.

Shadowing occurs when a local variable with the same name as a global variable is declared. This can lead to unexpected behavior.

To avoid shadowing, choose distinct names for local variables or explicitly use the global variable.

Another pitfall is incorrect type inference , where the inferred type is not what the programmer expected.

Always ensure the initial value accurately represents the desired type.

Using := outside of a function accidentally creates a new local variable in the global scope, which may lead to unused variables or compilation errors.

To modify a global variable, use = within functions.

Trying to use = without a prior declaration of the variable will result in an error. Ensure that the variable is declared before using = for assignment.

Declare the variable first or use := if declaring a new variable.

Avoiding these pitfalls involves careful consideration of the scope, understanding the nuances of := and = , and ensuring proper variable declarations. By being mindful of these aspects, programmers can effectively utilize both operators in Go.

Adopting best practices when using := and = in Go can significantly enhance the readability and maintainability of your code.

Clear And Concise Declarations

Minimizing global variables, consistent use of operators, avoiding unnecessary shadowing, type checking and initialization.

Use := for local variable declarations where type inference makes the code more concise. This not only saves space but also enhances readability.

This approach makes the function more readable and straightforward.

Limit the use of global variables . When necessary, use = to assign values to them and be cautious of accidental shadowing in local scopes.

Careful management of global variables helps in maintaining a clear code structure.

Be consistent in your use of := and = . Consistency aids in understanding the flow of variable declarations and assignments throughout your code.

Avoid shadowing unless intentionally used as part of the program logic. Use distinct names for local variables to prevent confusion.

Using distinct names enhances the clarity of the code.

Use := when you want to declare and initialize a variable in one line, and when the type is clear from the context. Ensure the initial value represents the desired type accurately.

This practice ensures that the type and intent of the variable are clear.

By following these best practices, you can effectively leverage the strengths of both := and = in Go, leading to code that is efficient, clear, and easy to maintain.

What distinguishes the capacity and length of a slice in Go?

In Go, a slice's capacity (cap) refers to the total number of elements the underlying array can hold, while its length (len) indicates the current number of elements in the slice. Slices are dynamic, resizing the array automatically when needed. The capacity increases as elements are appended beyond its initial limit, leading to a new, larger underlying array.

How can I stop VS Code from showing a warning about needing comments for my exported 'Agent' struct in Go?

To resolve the linter warning for your exported 'Agent' type in Go, add a comment starting with the type's name. For instance:

go // Agent represents... type Agent struct { name string categoryId int }

This warning occurs because Go's documentation generator, godoc, uses comments for auto-generating documentation. If you prefer not to export the type, declare it in lowercase:

go type agent struct { name string categoryId int }

You can find examples of documented Go projects on pkg.go.dev. If you upload your Go project to GitHub, pkg.go.dev can automatically generate its documentation using these comments. You can also include runnable code examples and more, as seen in go-doc tricks.

What is the difference between using *float64 and sql.NullFloat64 in Golang ORM for fields like latitude and longitude in a struct?

Russ Cox explains that there's no significant difference between using float64 and sql.NullFloat64. Both work fine, but sql.Null structs might express the intent more clearly. Using a pointer could give the garbage collector more to track. In debugging, sql.Null* structs display more readable values compared to pointers. Therefore, he recommends using sql.Null* structs.

Why doesn't auto-completion work for GO in VS Code with WSL terminal, despite having GO-related extensions installed?

Try enabling Go's Language Server (gopls) in VS Code settings. After enabling, restart VS Code. You may need to install or update gopls and other tools. Be aware that gopls is still in beta, so it may crash or use excessive CPU, but improvements are ongoing.

Let's see what you learned!

In Go, when should you use the := operator instead of the = operator?

Subscribe to our newsletter, subscribe to be notified of new content on marketsplash..

Go Tutorial

  • Go Tutorial
  • Go - Overview
  • Go - Environment Setup
  • Go - Program Structure
  • Go - Basic Syntax
  • Go - Data Types
  • Go - Variables
  • Go - Constants
  • Go - Operators
  • Go - Decision Making
  • Go - Functions
  • Go - Scope Rules
  • Go - Strings
  • Go - Arrays
  • Go - Pointers
  • Go - Structures
  • Go - Recursion
  • Go - Type Casting
  • Go - Interfaces
  • Go - Error Handling
  • Go Useful Resources
  • Go - Questions and Answers
  • Go - Quick Guide
  • Go - Useful Resources
  • Go - Discussion
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

Go - Assignment Operators

The following table lists all the assignment operators supported by Go language −

Try the following example to understand all the assignment operators available in Go programming language −

When you compile and execute the above program it produces the following result −

Golang Programs

Golang Tutorial

Golang reference, beego framework, golang operators.

An operator is a symbol that tells the compiler to perform certain actions. The following lists describe the different operators used in Golang.

  • Arithmetic Operators
  • Assignment Operators
  • Comparison Operators
  • Logical Operators
  • Bitwise Operators

Arithmetic Operators in Go Programming Language

The arithmetic operators are used to perform common arithmetical operations, such as addition, subtraction, multiplication etc.

Here's a complete list of Golang's arithmetic operators:

The following example will show you these arithmetic operators in action:

Assignment Operators in Go Programming Language

The assignment operators are used to assign values to variables

The following example will show you these assignment operators in action:

Comparison Operators in Go Programming Language

Comparison operators are used to compare two values.

The following example will show you these comparison operators in action:

Logical Operators in Go Programming Language

Logical operators are used to determine the logic between variables or values.

The following example will show you these logical operators in action:

Bitwise Operators in Go Programming Language

Bitwise operators are used to compare (binary) numbers.

The following example will show you these bitwise operators in action:

Most Helpful This Week

Learnmonkey Logo

Go Assignment Operators

What are assignment operators.

Assignment operators are used to assign variables to values.

The Assignment Operator ( = )

The equal sign that we are all familiar with is called the assignment operator, because it is the most important out of all the assignment operators. All the other assignment operators are built off of it. For example, the below code assigns the variable a the value of 3, the constant pi the value of 3.14, and the variable website the value of Learnmonkey:

Notice that we can use the assignment operator to make constants and variables. We can also use the assignment operator to set variables (not constants) once they are already created:

Other Assignment Operators

The other assignment operators were created so that as developers, our lives would be easier. They are all equivalent to using the assignment operator in some way:

  • Introduction to Go
  • Environment Setup
  • Your First Go Program
  • More on Printing
  • PyQt5 ebook
  • Tkinter ebook
  • SQLite Python
  • wxPython ebook
  • Windows API ebook
  • Java Swing ebook
  • Java games ebook
  • MySQL Java ebook

Go operators

last modified August 24, 2023

In this article we cover Go operators. We show how to use operators to create expressions.

We use Go version 1.18.

An operator is a special symbol which indicates a certain process is carried out. Operators in programming languages are taken from mathematics. Programmers work with data. The operators are used to process data. An operand is one of the inputs (arguments) of an operator.

Expressions are constructed from operands and operators. The operators of an expression indicate which operations to apply to the operands. The order of evaluation of operators in an expression is determined by the precedence and associativity of the operators.

An operator usually has one or two operands. Those operators that work with only one operand are called unary operators . Those who work with two operands are called binary operators .

Certain operators may be used in different contexts. For instance the + operator can be used in different cases: it adds numbers, concatenates strings, or indicates the sign of a number. We say that the operator is overloaded .

Go sign operators

There are two sign operators: + and - . They are used to indicate or change the sign of a value.

The + and - signs indicate the sign of a value. The plus sign can be used to signal that we have a positive number. It can be omitted and it is in most cases done so.

The minus sign changes the sign of a value.

Go assignment operator

The assignment operator = assigns a value to a variable. A variable is a placeholder for a value. In mathematics, the = operator has a different meaning. In an equation, the = operator is an equality operator. The left side of the equation is equal to the right one.

Here we assign a number to the x variable.

This expression does not make sense in mathematics, but it is legal in programming. The expression adds 1 to the x variable. The right side is equal to 2 and 2 is assigned to x .

This code line leads to a syntax error. We cannot assign a value to a literal.

Go has a short variable declaration operator := ; it declares a variable and assigns a value in one step. The x := 2 is equal to var x = 2 .

Go increment and decrement operators

We often increment or decrement a value by one in programming. Go has two convenient operators for this: ++ and -- .

In the above example, we demonstrate the usage of both operators.

We initiate the x variable to 6. Then we increment x two times. Now the variable equals to 8.

We use the decrement operator. Now the variable equals to 7.

Go compound assignment operators

The compound assignment operators consist of two operators. They are shorthand operators.

The += compound operator is one of these shorthand operators. The above two expressions are equal. Value 3 is added to the a variable.

Other compound operators include:

In the code example, we use two compound operators.

The a variable is initiated to one. 1 is added to the variable using the non-shorthand notation.

Using a += compound operator, we add 5 to the a variable. The statement is equal to a = a + 5 .

Using the *= operator, the a is multiplied by 3. The statement is equal to a = a * 3 .

Go arithmetic operators

The following is a table of arithmetic operators in Go.

The following example shows arithmetic operations.

In the preceding example, we use addition, subtraction, multiplication, division, and remainder operations. This is all familiar from the mathematics.

The % operator is called the remainder or the modulo operator. It finds the remainder of division of one number by another. For example, 9 % 4 , 9 modulo 4 is 1, because 4 goes into 9 twice with a remainder of 1.

Next we will show the distinction between integer and floating point division.

In the preceding example, we divide two numbers.

In this code, we have done integer division. The returned value of the division operation is an integer. When we divide two integers the result is an integer.

If one of the values is a double or a float, we perform a floating point division. In our case, the second operand is a double so the result is a double.

Go Boolean operators

In Go we have three logical operators.

Boolean operators are also called logical.

Many expressions result in a boolean value. For instance, boolean values are used in conditional statements.

Relational operators always result in a boolean value. These two lines print false and true.

The body of the if statement is executed only if the condition inside the parentheses is met. The y > x returns true, so the message "y is greater than x" is printed to the terminal.

The true and false keywords represent boolean literals in Go.

The code example shows the logical and (&&) operator. It evaluates to true only if both operands are true.

Only one expression results in true.

The logical or ( || ) operator evaluates to true if either of the operands is true.

If one of the sides of the operator is true, the outcome of the operation is true.

Three of four expressions result in true.

The negation operator ! makes true false and false true.

The example shows the negation operator in action.

Go comparison operators

Comparison operators are used to compare values. These operators always result in a boolean value.

comparison operators are also called relational operators.

In the code example, we have four expressions. These expressions compare integer values. The result of each of the expressions is either true or false. In Go we use the == to compare numbers. (Some languages like Ada, Visual Basic, or Pascal use = for comparing numbers.)

Go bitwise operators

Decimal numbers are natural to humans. 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.

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.

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

The bitwise or operator performs bit-by-bit comparison between two numbers. The result for a bit position is 1 if either of the corresponding bits in the operands is 1.

The result is 00110 or decimal 7.

The bitwise exclusive or operator performs bit-by-bit comparison between two numbers. The result for a bit position is 1 if one or the other (but not both) of the corresponding bits in the operands is 1.

The result is 00101 or decimal 5.

Go pointer operators

In Go, the & is an address of operator and the * is a pointer indirection operator.

In the code example, we demonstrate the two operators.

An integer variable is defined.

We get the address of the count variable; we create a pointer to the variable.

Via the pointer dereference, we modify the value of count.

Again, via pointer dereference, we print the value to which the pointer refers.

Go channel operator

A channels is a typed conduit through which we can send and receive values with the channel operator <- .

The example presents the channel operator.

We send a value to the channel.

We receive a value from the channel.

Go operator precedence

The operator precedence tells us which operators are evaluated first. The precedence level is necessary to avoid ambiguity in expressions.

What is the outcome of the following expression, 28 or 40?

Like in mathematics, the multiplication operator has a higher precedence than addition operator. So the outcome is 28.

To change the order of evaluation, we can use parentheses. Expressions inside parentheses are always evaluated first. The result of the above expression is 40.

In this code example, we show a few expressions. The outcome of each expression is dependent on the precedence level.

This line prints 28. The multiplication operator has a higher precedence than addition. First, the product of 5 * 5 is calculated, then 3 is added.

The evaluation of the expression can be altered by using round brackets. In this case, the 3 + 5 is evaluated and later the value is multiplied by 5. This line prints 40.

In this case, the negation operator has a higher precedence than the bitwise or. First, the initial true value is negated to false, then the | operator combines false and true, which gives true in the end.

Associativity rule

Sometimes the precedence is not satisfactory to determine the outcome of an expression. There is another rule called associativity . The associativity of operators determines the order of evaluation of operators with the same precedence level.

What is the outcome of this expression, 9 or 1? The multiplication, deletion, and the modulo operator are left to right associated. So the expression is evaluated this way: (9 / 3) * 3 and the result is 9.

Arithmetic, boolean and relational operators are left to right associated. The ternary operator, increment, decrement, unary plus and minus, negation, bitwise not, type cast, object creation operators are right to left associated.

In the code example, we the associativity rule determines the outcome of the expression.

The compound assignment operators are right to left associated. We might expect the result to be 1. But the actual result is 0. Because of the associativity. The expression on the right is evaluated first and then the compound assignment operator is applied.

In this article we have covered Go operators.

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

List all Go tutorials .

DEV Community

DEV Community

Meet Rajesh Gor

Posted on May 7, 2022 • Originally published at mr-destructive.github.io

Golang: Operators

Introduction.

In this 13th part of the series, we will be exploring the fundamentals of operators in Golang. We will be exploring the basics of operators and the various types like Arithmetic, Bitwise, Comparison, Assignment operators in Golang.

Operators are quite fundamentals in any programming language. Operators are basically expressions or a set of character(s) to perform certain fundamental tasks. They allow us to perform certain trivial operations with a simple expression or character. There are quite a few operators in Golang to perform various operations.

Types of Operators

Golang has a few types of operators, each type providing particular aspect of forming expressions and evaluate conditions.

Bitwise Operators

Logical operators, arithmetic operators, assignment operators, comparison operators.

Bitwise Operators are used in performing operations on binary numbers. We can perform operation on a bit level and hence they are known as bitwise operators. Some fundamental bitwise operators include, AND , OR , NOT , and EXOR . Using this operators, the bits in the operands can be manipulated and certain logical operations can be performed.

We use the & (AND operator) for performing AND operations on two operands. Here we are logically ANDing 3 and 5 i.e. 011 with 101 so it becomes 001 in binary or 1 in decimal.

Also, the | (OR operator) for performing logical OR operation on two operands. Here we are logically ORing 3 and 5 i.e. 011 with 101 so it becomes 111 in binary or 7 in decimal.

Also the ^ (EXOR operator) for performing logical EXOR operation on two operands. Here we are logically EXORing 3 and 5 i.e. 011 with 101 so it becomes 110 in binary or 6 in decimal.

We have a couple of more bitwise operators that allow us to shift bits in the binary representation of the number. We have two types of these shift operators, right sift and left shift operators. The main function of these operator is to shift a bit in either right or left direction.

In the above example, we have shifted 3 i.e. 011 to right by one bit so it becomes 001 . If we would have given x >> 2 it would have become 0 since the last bit was shifted to right and hence all bits were 0.

Similarly, the left shift operator sifts the bits in the binary representation of the number to the left. So, in the example above, 5 i.e. 101 is shifted left by one bit so it becomes 1010 in binary i.e. 10 in decimal.

This was a basic overview of bitwise operators in Golang. We can use these basic operators to perform low level operations on numbers.

This type of operators are quite important and widely used as they form the fundamentals of comparison of variables and forming boolean expressions. The comparison operator is used to compare two values or expressions.

We use simple comparison operators like == or != for comparing if two values are equal or not. The expression a == b will evaluate to true if the values of both variables or operands are equal. However, the expression a != b will evaluate to true if the values of both variables or operands are not equal.

Similarly, we have the < and > operators which allow us to evaluate expression by comparing if the values are less than or grater than the other operand. So, the expression a > b will evaluate to true if the value of a is greater than the value of b . Also the expression a < b will evaluate to true if the value of a is less than the value of b .

Finally, the operators <= and >= allow us to evaluate expression by comparing if the values are less than or equal to and greater than or equal to the other operand. So, the expression a >= b will evaluate to true if the value of a is greater than or if it is equal to the value of b , else it would evaluate to false . Similarly, the expression a <= b will evaluate to true if the value of a is less than or if it is equal to the value of b , else it would evaluate to false .

These was a basic overview of comparison operators in golang.

Next, we move on to the logical operators in Golang which allow to perform logical operations like AND , OR , and NOT with conditional statements or storing boolean expressions.

Here, we have used logical operators like && for Logical AND, || for logical OR, and ! for complementing the evaluated result. The && operation only evaluates to true if both the expressions are true and || OR operator evaluates to true if either or both the expressions are true . The ! operator is used to complement the evaluated expression from the preceding parenthesis.

Arithmetic operators are used for performing Arithmetic operations. We have few basic arithmetic operators like + , - , * , / , and % for adding, subtracting, multiplication, division, and modulus operation in golang.

These are the basic mathematical operators in any programming language. We can use + to add two values, - to subtract two values, * to multiply to values, / for division of two values and finally % to get the remainder of a division of two values i.e. if we divide 30 by 50, the remainder is 30 and the quotient is 0.

We also have a few other operators like ++ and -- that help in incrementing and decrementing values by a unit value. Let's say we have a variable k which is set to 4 and we want to increment it by one, so we can definitely use k = k + 1 but it looks kind of too long, we have a short notation for the same k++ to do the same.

So, we can see that the variable k is incremented by one and variable j is decremented by 1 using the ++ and -- operator.

These types of operators are quite handy and can condense down large operations into simple expressions. These types of operators allow us to perform operation on the same operand. Let's say we have the variable k set to 20 initially, we want to add 30 to the variable k , we can do that by using k = k + 30 but a more sophisticated way would be to use k += 30 which adds 30 or any value provided the same variable assigned and operated on.

From the above example, we are able to perform operations by using shorthand notations like += to add the value to the same operand. These also saves a bit of time and memory not much but considerable enough. This allow us to directly access and modify the contents of the provided operand in the register rather than assigning different registers and performing the operations.

That's it from this part. Reference for all the code examples and commands can be found in the 100 days of Golang GitHub repository.

So, from the following part of the series, we were able to learn the basics of operators in golang. Using some simple and easy to understand examples, we were able to explore different types of operators like arithmetic, logical, assignment and bitwise operators in golang. These are quite fundamental in programming in general, this lays a good foundation for working with larger and complex projects that deal with any kind of logic in it, without a doubt almost all of the applications do have a bit of logic attached to it. So, we need to know the basics of operators in golang.

Top comments (0)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

chigbeef_77 profile image

Bool -> Int But Stupid In Go

Chig Beef - Mar 9

aurelievache profile image

Learning Go by examples: part 12 - Deploy Go apps in Go with CDK for Terraform (CDKTF)

Aurélie Vache - Mar 7

phucvinh57 profile image

Tonic - Swaggo alternative

Nguyễn Phúc Vinh - Feb 17

sosalejandro profile image

Open Telemetry: Observing and Monitoring Applications

Alejandro Sosa - Mar 8

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Go Operators

Operators are symbols that allow us to perform various mathematical and logical operations on values and variables.

In Go, operators can be classified as below:

Arithmetic Operators

The arithmetic operators can be used in the basic arithmetic operations on literal values or variables.

The following example demonstrates arithmetic operations such as addition, subtraction, and modulus.

Comparison Operators

Comparison operators are used to compare two literal values or variables.

The following example demonstrates comparisons operators.

Logical Operators:

The logical operators are used to perform logical operations by combining two or more conditions. They return either true or false depending upon the conditions.

The following example demonstrates the logical operators.

Bitwise Operators

The bitwise operators work on bits and perform bit-by-bit operation.

The following example demonstrates the bitwise operations.

In the above example, two int variables are x = 3 and y = 5 . Binary of 3 is 0011 and 5 is 0101. so, x & y is 0001, which is numeric 1. x | y is 0111 which is numeric 7, and x ^ y is 0110 which is numeric 6.

Assignment Operators

The assignment operators are used to assign literal values or assign values by performing some arithmetic operation using arithmetic operators.

The following example demonstrates the assignment operators.

.NET Tutorials

Database tutorials, javascript tutorials, programming tutorials.

  • Trending Now
  • Foundational Courses
  • Data Science
  • Practice Problem
  • Machine Learning
  • System Design
  • DevOps Tutorial
  • Go Programming Language (Introduction)
  • How to Install Go on Windows?
  • How to Install Golang on MacOS?
  • Hello World in Golang

Fundamentals

  • Identifiers in Go Language
  • Go Keywords
  • Data Types in Go
  • Go Variables
  • Constants- Go Language

Go Operators

Control statements.

  • Go Decision Making (if, if-else, Nested-if, if-else-if)
  • Loops in Go Language
  • Switch Statement in Go

Functions & Methods

  • Functions in Go Language
  • Variadic Functions in Go
  • Anonymous function in Go Language
  • main and init function in Golang
  • What is Blank Identifier(underscore) in Golang?
  • Defer Keyword in Golang
  • Methods in Golang
  • Structures in Golang
  • Nested Structure in Golang
  • Anonymous Structure and Field in Golang
  • Arrays in Go
  • How to Copy an Array into Another Array in Golang?
  • How to pass an Array to a Function in Golang?
  • Slices in Golang
  • Slice Composite Literal in Go
  • How to sort a slice of ints in Golang?
  • How to trim a slice of bytes in Golang?
  • How to split a slice of bytes in Golang?
  • Strings in Golang
  • How to Trim a String in Golang?
  • How to Split a String in Golang?
  • Different ways to compare Strings in Golang
  • Pointers in Golang
  • Passing Pointers to a Function in Go
  • Pointer to a Struct in Golang
  • Go Pointer to Pointer (Double Pointer)
  • Comparing Pointers in Golang

Concurrency

  • Goroutines - Concurrency in Golang
  • Select Statement in Go Language
  • Multiple Goroutines
  • Channel in Golang
  • Unidirectional Channel in Golang

Operators are the foundation of any programming language. Thus the functionality of the Go language is incomplete without the use of operators. Operators allow us to perform different kinds of operations on operands. In the Go language , operators Can be categorized based on their different functionality:

Arithmetic Operators

Relational operators, logical operators, bitwise operators, assignment operators, misc operators.

These are used to perform arithmetic/mathematical operations on operands in Go language: 

  • Addition: The ‘+’ operator adds two operands. For example, x+y.
  • Subtraction: The ‘-‘ operator subtracts two operands. For example, x-y.
  • Multiplication: The ‘*’ operator multiplies two operands. For example, x*y.
  • Division: The ‘/’ operator divides the first operand by the second. For example, x/y.
  • Modulus: The ‘%’ operator returns the remainder when the first operand is divided by the second. For example, x%y.
Note: -, +, !, &, *, <-, and ^ are also known as unary operators and the precedence of unary operators is higher. ++ and — operators are from statements they are not expressions, so they are out from the operator hierarchy.

Example:  

Output:  

Relational operators are used for the comparison of two values. Let’s see them one by one:

  • ‘=='(Equal To) operator checks whether the two given operands are equal or not. If so, it returns true. Otherwise, it returns false. For example, 5==5 will return true.
  • ‘!='(Not Equal To) operator checks whether the two given operands are equal or not. If not, it returns true. Otherwise, it returns false. It is the exact boolean complement of the ‘==’ operator. For example, 5!=5 will return false.
  • ‘>'(Greater Than) operator checks whether the first operand is greater than the second operand. If so, it returns true. Otherwise, it returns false. For example, 6>5 will return true.
  • ‘<‘(Less Than) operator checks whether the first operand is lesser than the second operand. If so, it returns true. Otherwise, it returns false. For example, 6<5 will return false.
  • ‘>='(Greater Than Equal To) operator checks whether the first operand is greater than or equal to the second operand. If so, it returns true. Otherwise, it returns false. For example, 5>=5 will return true.
  • ‘<='(Less Than Equal To) operator checks whether the first operand is lesser than or equal to the second operand. If so, it returns true. Otherwise, it returns false. For example, 5<=5 will also return true.

They are used to combine two or more conditions/constraints or to complement the evaluation of the original condition in consideration.  

  • Logical AND: The ‘&&’ operator returns true when both the conditions in consideration are satisfied. Otherwise it returns false. For example, a && b returns true when both a and b are true (i.e. non-zero).
  • Logical OR: The ‘||’ operator returns true when one (or both) of the conditions in consideration is satisfied. Otherwise it returns false. For example, a || b returns true if one of a or b is true (i.e. non-zero). Of course, it returns true when both a and b are true.
  • Logical NOT: The ‘!’ operator returns true the condition in consideration is not satisfied. Otherwise it returns false. For example, !a returns true if a is false, i.e. when a=0.

In Go language, there are 6 bitwise operators which work at bit level or used to perform bit by bit operations. Following are the bitwise operators : 

  • & (bitwise AND): Takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.
  • | (bitwise OR): Takes two numbers as operands and does OR on every bit of two numbers. The result of OR is 1 any of the two bits is 1.
  • ^ (bitwise XOR): Takes two numbers as operands and does XOR on every bit of two numbers. The result of XOR is 1 if the two bits are different.
  • << (left shift): Takes two numbers, left shifts the bits of the first operand, the second operand decides the number of places to shift.
  • >> (right shift): Takes two numbers, right shifts the bits of the first operand, the second operand decides the number of places to shift.
  • &^ (AND NOT): This is a bit clear operator.

Assignment operators are used to assigning a value to a variable. The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value. The value on the right side must be of the same data-type of the variable on the left side otherwise the compiler will raise an error. Different types of assignment operators are shown below:

  • “=”(Simple Assignment): This is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left.
  • “+=”(Add Assignment): This operator is a combination of ‘+’ and ‘=’ operators. This operator first adds the current value of the variable on left to the value on the right and then assigns the result to the variable on the left.
  • “-=”(Subtract Assignment): This operator is a combination of ‘-‘ and ‘=’ operators. This operator first subtracts the current value of the variable on left from the value on the right and then assigns the result to the variable on the left.
  • “*=”(Multiply Assignment): This operator is a combination of ‘*’ and ‘=’ operators. This operator first multiplies the current value of the variable on left to the value on the right and then assigns the result to the variable on the left.
  • “/=”(Division Assignment): This operator is a combination of ‘/’ and ‘=’ operators. This operator first divides the current value of the variable on left by the value on the right and then assigns the result to the variable on the left.
  • “%=”(Modulus Assignment): This operator is a combination of ‘%’ and ‘=’ operators. This operator first modulo the current value of the variable on left by the value on the right and then assigns the result to the variable on the left.
  • “&=”(Bitwise AND Assignment): This operator is a combination of ‘&’ and ‘=’ operators. This operator first “Bitwise AND” the current value of the variable on the left by the value on the right and then assigns the result to the variable on the left.
  • “^=”(Bitwise Exclusive OR): This operator is a combination of ‘^’ and ‘=’ operators. This operator first “Bitwise Exclusive OR” the current value of the variable on left by the value on the right and then assigns the result to the variable on the left.
  • “|=”(Bitwise Inclusive OR): This operator is a combination of ‘|’ and ‘=’ operators. This operator first “Bitwise Inclusive OR” the current value of the variable on left by the value on the right and then assigns the result to the variable on the left.
  • “<<=”(Left shift AND assignment operator): This operator is a combination of ‘<<’ and ‘=’ operators. This operator first “Left shift AND” the current value of the variable on left by the value on the right and then assigns the result to the variable on the left.
  • “>>=”(Right shift AND assignment operator): This operator is a combination of ‘>>’ and ‘=’ operators. This operator first “Right shift AND” the current value of the variable on left by the value on the right and then assigns the result to the variable on the left.
  • &: This operator returns the address of the variable.
  • *: This operator provides pointer to a variable.
  • <-: The name of this operator is receive. It is used to receive a value from the channel.

Please Login to comment...

Similar reads.

author

  • What are Tiktok AI Avatars?
  • Poe Introduces A Price-per-message Revenue Model For AI Bot Creators
  • Truecaller For Web Now Available For Android Users In India
  • Google Introduces New AI-powered Vids App
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IncludeHelp_logo

  • Data Structure
  • Coding Problems
  • C Interview Programs
  • C++ Aptitude
  • Java Aptitude
  • C# Aptitude
  • PHP Aptitude
  • Linux Aptitude
  • DBMS Aptitude
  • Networking Aptitude
  • AI Aptitude
  • MIS Executive
  • Web Technologie MCQs
  • CS Subjects MCQs
  • Databases MCQs
  • Programming MCQs
  • Testing Software MCQs
  • Digital Mktg Subjects MCQs
  • Cloud Computing S/W MCQs
  • Engineering Subjects MCQs
  • Commerce MCQs
  • More MCQs...
  • Machine Learning/AI
  • Operating System
  • Computer Network
  • Software Engineering
  • Discrete Mathematics
  • Digital Electronics
  • Data Mining
  • Embedded Systems
  • Cryptography
  • CS Fundamental
  • More Tutorials...
  • Tech Articles
  • Code Examples
  • Programmer's Calculator
  • XML Sitemap Generator
  • Tools & Generators

IncludeHelp

Home » Golang

Golang Assignment Operators

Here, we are going to learn about the Assignment Operators in the Go programming language with examples. Submitted by IncludeHelp , on December 08, 2021

Assignment Operators

Assignment operators are used for assigning the expressions or values to the variable/ constant etc. These operators assign the result of the right-side expression to the left-side variable or constant. The " = " is an assignment operator. Assignment operators can also be the combinations of some other operators (+, -, *, /, %, etc.) and " = ". Such operators are known as compound assignment operators .

List of Golang Assignment Operators

Example of golang assignment operators.

The below Golang program is demonstrating the example of assignment operators.

Comments and Discussions!

Load comments ↻

  • Marketing MCQs
  • Blockchain MCQs
  • Artificial Intelligence MCQs
  • Data Analytics & Visualization MCQs
  • Python MCQs
  • C++ Programs
  • Python Programs
  • Java Programs
  • D.S. Programs
  • Golang Programs
  • C# Programs
  • JavaScript Examples
  • jQuery Examples
  • CSS Examples
  • C++ Tutorial
  • Python Tutorial
  • ML/AI Tutorial
  • MIS Tutorial
  • Software Engineering Tutorial
  • Scala Tutorial
  • Privacy policy
  • Certificates
  • Content Writers of the Month

Copyright © 2024 www.includehelp.com. All rights reserved.

Learn Golang Operators Guide with examples

  • Dec 31, 2023

Learn Golang Operators Guide with examples

# Go Language Operators

Like many programming languages, Golang has support for various inbuilt operators.

Important keynotes of operators in the Go language

  • Operators are character sequences used to execute some operations on a given operand(s)
  • Each operator in the Go language is of types Unary Operator or Binary Operator. Binary operators accept two operands, Unary Operator accepts one operand
  • Operators operate on one or two operands with expressions
  • These are used to form expressions

The following are different types covered as part of this blog post.

  • Arithmetic Operators
  • Relational Operators
  • Logical Operators
  • Bitwise Operators
  • Assignment Operator
  • Address Operators
  • Other Operators
  • Operator Precedence

Operators syntax :

There are two types of operators

  • unary - applies to the single operand
  • binary - applies to two operands.

Here is a Unary Operator Syntax

Here is a Binary Operator Syntax

The operand is data or variables that need to be manipulated.

# Golang Arithmetic Operators

Arithmetic operators perform arithmetic calculations like addition, multiplication, subtract, on numeric values. Assume that Operands a and b values are 10,5.

Four operators (+,-,*,/) operate on Numeric types such as Integer and Float , Complex . + operator on String. ++ and -- operators on Numeric types.

Following is an example for the usage of Arithmetic operators

The output of the above program code execution is

# Golang Comparison or Relational Operators

Comparison operators are used to compare the operands in an expression. Operands can be named type and compared operand of same type or values of the same type.

These operators enclosed in ( and ) i.e (a==b) , If it is not enclosed - a == b gives compilation error - cannot use a == b (type bool) as type int in assignment Operands of any type as mentioned in below keynotes. And returned value of this comparison is untyped a boolean value - true or false.

Keynotes of Comparison Operators

  • All primitive types (Integers, Floats, Boolean, String) are comparable
  • Complex data types, Channel Pointer can be used to compare with these
  • Interfaces can be comparable and return true - if both interfaces are of the same dynamic type, values, or nil, else return false
  • if Structs can be comparable and returns true - properties or fields are equal
  • if arrays compared with this, returns true - if both array values are equal

Following are a list of Go Inbuilt Comparison Operators

Below is a Golang comparison operators example

When the above program is compiled and executed outputs the below results

# Golang Logical Operators

Logical operators accept the Boolean value and return a Boolean value.

It contains Left and Right Operands. If Left Operand is evaluated to true, Right Operand will not be evaluated.

These are called short circuit rules, if both operands (1 && 1)are not Boolean, and gives compilation error invalid operation: 1 && 1 (operator && not defined on untyped number)

Following is a list of operators supported in the Go language.

Here is an example of Logical Operator usage

Compilation and running of the above is

# Golang Bitwise Operators

These operators are used with bit manipulation. Go language has supported different bitwise operators. It operates on bits only. Generate true table manipulation values on bits 0 and 1

Following is a List of Bitwise Operators supported in Go

Here is an example for Logical Operator example

# Golang Assignment Operators

Assignment operators are used to perform the calculation of some operations and finally result is assigned to the left side operand.

Golang has support for multiple assignment operators

Following is an example of Using assignment Operators

When the above program code is compiled and executed, Output is

# Golang Address Operators

There are two operators related address of a variable asterisk * Operator These are used to give a pointer of a variable and dereference pointer which gives a pointer to a point of points.

Ampersand & Operator This gives the address of a variable. It gives the actual location of the variable saved in memory. Here is an example of Asterisk and Ampersand Operator

The output of the above programs is

# Golang Operator Precedence

In any expression, multiple operators are applied, Precedence decides the evaluation order on which operators run first. Unary Operators rank the highest precedence than binary operators. You can check official documentation [here] https://golang.org/ref/spec 🔗 .

Mastering Golang: Mathematical Operators

  • July 2, 2023

Luke Barber

Go (Golang) logo with 'Math Operators' text

Performing Arithmetic Operations

Mathematical operations are fundamental in programming. In this post, we’ll delve into the world of arithmetic calculations using math operators in Golang . Understanding these operators is essential for performing calculations and manipulating numerical data within Golang programs.

Basic Math Operators

Go supports a variety of math operators for performing arithmetic operations. Here’s a list of the basic math operators supported by Go:

  • Addition: +
  • Subtraction: -
  • Multiplication: *
  • Division: /
  • Remainder (Modulus): %

Basic Examples

Let’s quickly go through some examples of each one:

Addition (+):

Adds two numbers together.

Subtraction (-):

Subtracts the right operand from the left operand.

Multiplication (*):

Multiplies two numbers.

Division (/):

Divides the left operand by the right operand.

Remainder (%):

Calculates the remainder after division.

Exponentiation (**):

Go doesn’t have a built-in exponentiation operator like some other languages. Instead, you can achieve exponentiation using the math.Pow function from the math package.

Code Example

Here’s a complete example of how you can use these operators in Go:

Assignment Operators

Additionally, Go also has some shorthand assignment operators that combine arithmetic operations with variable assignments. Here are a few examples:

  • ++ : Add 1 (Increment)
  • -- : Subtract 1 (Decrement)
  • += : Add and assign
  • -= : Subtract and assign
  • *= : Multiply and assign
  • /= : Divide and assign
  • %= : Calculate remainder and assign

Golang Math Package

Go’s math package provides various mathematical functions beyond simple arithmetic.

For Example:

Bitwise Operators

While not strictly related to advanced math, Go also supports bitwise operators that manipulate individual bits in integers.

Arithmetic operations are fundamental in programming, and Golang provides a range of math operators to perform these operations efficiently. Understanding and utilizing these operators enables you to perform calculations, manipulate numeric data, and build more complex algorithms within your Golang programs.

That’s All Folks!

You can find all of our Golang guides here: A Comprehensive Guide to Golang

' data-src=

Hello, fellow tech enthusiasts! I'm Luke, a passionate learner and explorer in the vast realms of technology. Welcome to my digital space where I share the insights and adventures gained from my journey into the fascinating worlds of Arduino, Python, Linux, Ethical Hacking, and beyond. Armed with qualifications including CompTIA A+, Sec+, Cisco CCNA, Unix/Linux and Bash Shell Scripting, JavaScript Application Programming, Python Programming and Ethical Hacking, I thrive in the ever-evolving landscape of coding, computers, and networks. As a tech enthusiast, I'm on a mission to simplify the complexities of technology through my blogs, offering a glimpse into the marvels of Arduino, Python, Linux, and Ethical Hacking techniques. Whether you're a fellow coder or a curious mind, I invite you to join me on this journey of continuous learning and discovery.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

Related Articles

nRF24L01 with Arduino Nano Diagram

NRF24L01: Building your First Radio with Arduino

NRF24L01 Radio Module with Onboard Antenna

NRF24L01 Radio Module for Beginners

Morse code project with arduino.

Operators in Go self.__wrap_b=(t,n,e)=>{e=e||document.querySelector(`[data-br="${t}"]`);let a=e.parentElement,r=R=>e.style.maxWidth=R+"px";e.style.maxWidth="";let o=a.clientWidth,c=a.clientHeight,i=o/2-.25,l=o+.5,u;if(o){for(;i+1 {self.__wrap_b(0,+e.dataset.brr,e)})).observe(a):process.env.NODE_ENV==="development"&&console.warn("The browser you are using does not support the ResizeObserver API. Please consider add polyfill for this API to avoid potential layout shifts or upgrade your browser. Read more: https://github.com/shuding/react-wrap-balancer#browser-support-information"))};self.__wrap_b(":R4mr36:",1)

Pranav's profile image

Introduction to Go and Operators

Basic operators, logical operators, bitwise operators, unary operators.

Operators in Go

Go, often referred to as Golang, is a statically typed, compiled programming language designed at Google. Renowned for its simplicity, efficiency, and reliability, Go has become a preferred choice for building fast, scalable, and robust applications. One of the fundamental aspects of Go that contributes to its power and versatility is the use of operators. Operators are special symbols or keywords that are capable of manipulating individual data items, known as operands.

Developed to address the shortcomings of other programming languages, Go offers a rich set of features like garbage collection, structural typing, and CSP-style concurrency. While the language is minimalistic and straightforward, its operators play a pivotal role in performing various operations, ranging from basic mathematical calculations to complex decision making. Understanding how operators work and their precedence is crucial for writing efficient and effective Go code.

Operators in Go are divided into several categories based on the functionality they offer. These include arithmetic, assignment, comparison, logical, bitwise, and unary operators. Each category serves a specific purpose and helps in manipulating data in different ways.

Arithmetic Operators

Arithmetic operators are used to perform basic mathematical operations. These include:

  • Addition ( + ): Adds two operands.
  • Subtraction ( - ): Subtracts the second operand from the first.
  • Multiplication ( * ): Multiplies both operands.
  • Division ( / ): Divides the numerator by the denominator.
  • Modulus ( % ): Returns the remainder when the first operand is divided by the second.

These operators are straightforward and similar to those in other programming languages, making them easy to understand and use.

Assignment Operators

Assignment operators are used to assign values to variables. In Go, the basic assignment operator is = . However, there are shorthand operators that combine arithmetic and assignment, which not only make the code more concise but also improve its readability. These include:

  • += : Adds and assigns.
  • -= : Subtracts and assigns.
  • *= : Multiplies and assigns.
  • /= : Divides and assigns.
  • %= : Modulus and assigns.

Comparison Operators

Comparison operators are crucial in decision-making processes. They compare two operands and return a boolean value ( true or false ). The comparison operators in Go include:

  • Equal to ( == ): Returns true if the operands are equal.
  • Not equal to ( != ): Returns true if the operands are not equal.
  • Less than ( < ): Returns true if the left operand is less than the right operand.
  • Greater than ( > ): Returns true if the left operand is greater than the right operand.
  • Less than or equal to ( <= ): Returns true if the left operand is less than or equal to the right operand.
  • Greater than or equal to ( >= ): Returns true if the left operand is greater than or equal to the right operand.

Logical operators are used to combine conditional statements. The logical operators in Go are:

  • AND ( && ): Returns true if both operands are true.
  • OR ( || ): Returns true if at least one of the operands is true.
  • NOT ( ! ): Reverses the logic of the operand. Returns true if the operand is false and vice versa.

These operators are instrumental in constructing complex logical conditions and are widely used in conditional and loop statements.

Bitwise operators allow manipulation of individual bits of data. They perform bit-level operations on operands. The bitwise operators in Go include:

  • AND ( & ): Performs a bitwise AND.
  • OR ( | ): Performs a bitwise OR.
  • XOR ( ^ ): Performs a bitwise XOR.
  • AND NOT ( &^ ): Clears the bits (in the first operand) that are set in the second operand.
  • Left shift ( << ): Shifts the bits of the first operand to the left by the number of positions specified by the second operand.
  • Right shift ( >> ): Shifts the bits of the first operand to the right by the number of positions specified by the second operand.

Bitwise operators are primarily used in low-level programming, such as systems programming and writing device drivers.

Unary operators operate on a single operand. In Go, the unary operators include:

  • Increment ( ++ ): Increases the integer value by one. Can be used as a prefix or postfix (e.g., ++i or i++ ).
  • Decrement ( -- ): Decreases the integer value by one. Can also be used as a prefix or postfix (e.g., --i or i-- ).
  • Unary plus ( + ): Indicates a positive value (though not necessary to use explicitly).
  • Unary minus ( - ): Negates the value of the operand.

While unary operators are simple, they are quite powerful and are frequently used in loops and conditional statements.

Ternary Operator

Unlike many other languages, Go does not support the traditional ternary operator ( condition ? true : false ). This design decision aligns with Go’s philosophy of simplicity and clarity. Instead of using a ternary operator, Go encourages the use of if-else statements to make decisions in code. This approach ensures that control structures are explicit and easy to read. For example:

This explicitness is favored in Go to improve code readability and maintainability.

Type Operators

Go provides two main operators for dealing with types: type conversion and type assertion.

Type Conversion: In Go, converting one type into another is done explicitly to ensure that the programmer is aware of the conversion and its potential implications. The syntax for type conversion is Type(value) . For example, converting an int to a float64 :

Type Assertion: Type assertion is used with interfaces to extract the underlying concrete value of the interface. The syntax is interfaceValue.(Type) . This is particularly useful when you need to access a specific method of the underlying type. For example:

Type assertion can panic if the assertion is invalid, highlighting the importance of using it carefully or employing the two-value form to safely test for a successful assertion.

Operator Precedence

Operator precedence determines the order in which operators are evaluated. Go’s operator precedence is similar to that of many C-like languages. Multiplicative operators ( * , / , % , << , >> , & , &^ ) have higher precedence than additive operators ( + , - , | , ^ ), which in turn have higher precedence than comparison operators ( == , != , < , <= , > , >= ), and so forth.

Understanding precedence is crucial to correctly interpreting complex expressions without relying on parentheses. However, when in doubt, using parentheses can clarify the intended order of operations and improve code readability.

Sharing is caring

Did you like what Pranav wrote? Thank them for their work by sharing it on social media.

No comment s so far

Curious about this topic? Continue your journey with these coding courses:

Course thumbnail for Golang - Getting Started

Ayush Srivastav

Golang - Getting Started

Course thumbnail for Go Programming Bootcamp

Derek Banas

Go Programming Bootcamp

Course thumbnail for Build web apps with Go

Build web apps with Go

Golang Operators

In the programming world, the operator is considered a symbol that is used for performing different operations on the value or any variable in the Go language. In this article, we will be learning about different operators in the Go language along with their examples.

What are the Operators in Golang?

The operator in any programming language is a foundation and thus is an important part of the Go language. The Go language has functionality incomplete without operators. The use of operators allows the developers to perform various different kinds of operations on the operand.

What Are the Different Types of Operators in Golang?

The operators in the Go language are of a different type that is categorized into the following type on the basis of the functionality that the operator provides:

  • Arithmetic operators
  • Relational operators
  • Logical operators
  • Bitwise operators
  • Assignment operators
  • Miscellaneous operators

Arithmetic Operators

These are used for performing different arithmetic and mathematical operations on variables or operands in the Go language.

Description of Different Operators

  • Addition- It is used for adding two numbers.
  • Subtraction- It is used for subtracting two numbers.
  • Multiplication- It is used for multiplying two numbers.
  • Division- It is used for dividing one number by another.
  • Modulo Division- It is used for dividing two numbers and the resultant reminder is the output of the modulo division operation.

Relational Operators

This operator is used for comparing two different values or variables.

In this, the == operator is the relational operator that is used for checking if the values a and b are equal or not. The relational operator returns true if the two values are equal else it returns false if the two values are not equal.

  • == (equal to)
  • != (not equal to)
  • > (greater than)
  • < (less than)
  • >= (greater than or equal to)
  • <= (less than or equal to)

Assume a=10 and b=20

Logical Operators

These operators are used for performing logical related operations. Depending upon the condition, the logical operator returns true or false.

  • && (Logical AND)
  • || (Logical OR)
  • ! (Logical NOT)

Bitwise Operators

There are 6 bitwise operators in the Go language and it works at a bit level or performs bit-by-bit operations.

Assume int a=8 and b=13

  • & (bitwise AND)
  • | (bitwise OR)
  • ^ (bitwise XOR)
  • << (left shift)
  • >> (right shift)
  • &^ (AND NOT)

Go program to illustrate the use of bitwise operators

Assignment Operators

These operators are used for assigning the value to a variable. The left side of the operand contains the variable whereas the right side contains the assignment operator along with the value. The error is popped up if the data type and variable are not of the same type.

  • += (addition assignment)
  • -= (subtraction assignment)
  • *= (multiplication assignment)
  • /= (division assignment)
  • %= (modulo assignment)

Miscellaneous Operators

There are three types of miscellaneous operators.

  • & : This operator is used for returning the address of the variable.
  • * : This operator is used for providing the pointer to the variable.
  • <- This is also known as receive operator and is used for receiving the value from the channel.

Operator's Precedence in Golang

The operator's precedence in golang is used for determining the grouping of the terms in an expression which affects the expression that is evaluated in golang. There are few operators that have high precedence over other operators, for instance, the multiplication operator has higher precedence when compared to the addition operator in any programming language.

Below given is the list of operators along with their precedence.

  • The operator in any programming language is a foundation and thus is an important part of the Go language.
  • The Go language has functionality incomplete without operators. The use of operators allows the developers to perform various different kinds of operations on the operand.

IMAGES

  1. Golang Tutorial #6

    golang operators in assignment

  2. golang

    golang operators in assignment

  3. How To Use Operators With Numbers In GO Programming Language

    golang operators in assignment

  4. Golang Variables Declaration, Assignment and Scope Tutorial

    golang operators in assignment

  5. Go Tutorial (Golang) 6

    golang operators in assignment

  6. Golang Operators

    golang operators in assignment

VIDEO

  1. Tutorial # 16 Arithmetic Operators

  2. golang context package explained: the package that changed concurrency forever

  3. The new Golang 1.22 net/http package enables wildcard routing!

  4. #20. Assignment Operators in Java

  5. Golang Tutorial #3

  6. Introduction to Kubernetes operators in Go

COMMENTS

  1. Go Assignment Operators

    Assignment operators are used to assign values to variables. In the example below, we use the assignment operator (=) to assign the value 10 to a variable called x: Example. package main import ("fmt") func main() { var x = 10 fmt.Println(x)}

  2. syntax

    A short variable declaration uses the syntax: ShortVarDecl = IdentifierList ":=" ExpressionList . It is a shorthand for a regular variable declaration with initializer expressions but no types: "var" IdentifierList = ExpressionList . Assignments. Assignment = ExpressionList assign_op ExpressionList . assign_op = [ add_op | mul_op ] "=" .

  3. Go Operators (With Examples)

    In Go, we can also use an assignment operator together with an arithmetic operator. For example, number := 2 number += 6. Here, += is additional assignment operator. It first adds 6 to the value of number (2) and assigns the final result (8) to number. Here's a list of various compound assignment operators available in Golang.

  4. The Go Programming Language Specification

    The shift operators shift the left operand by the shift count specified by the right operand, which must be non-negative. If the shift count is negative at run time, a run-time panic occurs. The shift operators implement arithmetic shifts if the left operand is a signed integer and logical shifts if it is an unsigned integer.

  5. Golang := Vs = Exploring Assignment Operators In Go

    The assignment operator, =, in Go, is used to assign values to already declared variables. Unlike :=, it does not declare a new variable but modifies the value of an existing one. For example: var age int. age = 30. Here, age is first declared as an integer, and then 30 is assigned to it using =.

  6. Go

    The following table lists all the assignment operators supported by Go language −. Operator. Description. Example. =. Simple assignment operator, Assigns values from right side operands to left side operand. C = A + B will assign value of A + B into C. +=. Add AND assignment operator, It adds right operand to the left operand and assign the ...

  7. How To Do Math in Go with Operators

    Go has a compound assignment operator for each of the arithmetic operators discussed in this tutorial. To add then assign the value: y += 1. To subtract then assign the value: ... (or GoLang) is a modern programming language originally developed by Google that uses high-level syntax similar to scripting languages. It is popular for its minimal ...

  8. 7 Types of Golang Operators

    An operator is a symbol that tells the compiler to perform certain actions. The following lists describe the different operators used in Golang. Arithmetic Operators. Assignment Operators. Comparison Operators. Logical Operators. Bitwise Operators.

  9. Go Assignment Operators

    All the other assignment operators are built off of it. For example, the below code assigns the variable a the value of 3, the constant pi the value of 3.14, and the variable website the value of Learnmonkey: var a = 3 const pi = 3.14 var website = "Learnmonkey". Notice that we can use the assignment operator to make constants and variables.

  10. operators, expressions, precedence, associativity in Golang

    The operators of an expression indicate which operations to apply to the operands. The order of evaluation of operators in an expression is determined by the precedence and associativity of the operators. An operator usually has one or two operands. Those operators that work with only one operand are called unary operators .

  11. A Tour of Go

    Inside a function, the := short assignment statement can be used in place of a var declaration with implicit type. Outside a function, every statement begins with a keyword ( var, func, and so on) and so the := construct is not available. < 10/17 >. short-variable-declarations.go Syntax Imports.

  12. Golang: Operators

    We will be exploring the basics of operators and the various types like Arithmetic, Bitwise, Comparison, Assignment operators in Golang. Operators are quite fundamentals in any programming language. Operators are basically expressions or a set of character(s) to perform certain fundamental tasks. They allow us to perform certain trivial ...

  13. Go lang Operators: Arithmetic, Comparison, Logical, Bitwise, Assignment

    Assignment Operators. The assignment operators are used to assign literal values or assign values by performing some arithmetic operation using arithmetic operators. The following example demonstrates the assignment operators. import "fmt" func main() {. x, y := 10, 20 //Assign. x = y. fmt.Println(" = ", x) //output: 20 // Add and assign. x = 15.

  14. Go Operators

    Different types of assignment operators are shown below: "="(Simple Assignment): This is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left. "+="(Add Assignment): This operator is a combination of '+' and '=' operators. This operator first adds the current value ...

  15. Golang Assignment Operators

    These operators assign the result of the right-side expression to the left-side variable or constant. The "=" is an assignment operator. Assignment operators can also be the combinations of some other operators (+, -, *, /, %, etc.) and "=". Such operators are known as compound assignment operators. List of Golang Assignment Operators

  16. Learn Golang Operators Guide with examples

    #Golang Assignment Operators; #Golang Address Operators; #Golang Operator Precedence # Go Language Operators. Like many programming languages, Golang has support for various inbuilt operators. Important keynotes of operators in the Go language. Operators are character sequences used to execute some operations on a given operand(s)

  17. Operators In Go

    In this video we'll learn about the main operators in Golang.We'll look at math operators (arithmetic operators), assignment operators, and comparison operat...

  18. Mastering Golang: Mathematical Operators

    "Explore Golang's math operators for performing arithmetic operations like addition, subtraction, multiplication, division, and more in your Golang programs." ... Assignment Operators. Additionally, Go also has some shorthand assignment operators that combine arithmetic operations with variable assignments. Here are a few examples:

  19. Operators in Go

    Go, often referred to as Golang, is a statically typed, compiled programming language designed at Google. Renowned for its simplicity, efficiency, and reliability, Go has become a preferred choice for building fast, scalable, and robust applications. ... Assignment operators are used to assign values to variables. In Go, the basic assignment ...

  20. go

    The one statement multiple assignment, which uses implicit temporary variables, is equivalent to (a shorthand for) the two multiple assignment statements, which use explicit temporary variables. Your fibonacci example translates, with explicit order and temporary variables, to: package main. import "fmt". func fibonacciMultiple() func() int {.

  21. Golang Operators- Scaler Topics

    The operator's precedence in golang is used for determining the grouping of the terms in an expression which affects the expression that is evaluated in golang. There are few operators that have high precedence over other operators, for instance, the multiplication operator has higher precedence when compared to the addition operator in any ...