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

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, 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 assignment operator

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..

  • 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 .

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

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.

golang assignment operator

We are a team of passionate developers, educators, and technology enthusiasts who, with their combined expertise and experience, create in -depth, comprehensive, and easy to understand tutorials.We focus on a blend of theoretical explanations and practical examples to encourages hands - on learning. Visit About Us page for more information.

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.

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

  • 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

  • How to Organize Your Digital Files with Cloud Storage and Automation
  • 10 Best Blender Alternatives for 3D Modeling in 2024
  • How to Transfer Photos From iPhone to iPhone
  • What are Tiktok AI Avatars?
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

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

An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. Go language is rich in built-in operators and provides the following types of operators −

Arithmetic Operators

Relational operators, logical operators, bitwise operators, assignment operators, miscellaneous operators.

This tutorial explains arithmetic, relational, logical, bitwise, assignment, and other operators one by one.

Following table shows all the arithmetic operators supported by Go language. Assume variable A holds 10 and variable B holds 20 then −

Show Examples

The following table lists all the relational operators supported by Go language. Assume variable A holds 10 and variable B holds 20, then −

The following table lists all the logical operators supported by Go language. Assume variable A holds 1 and variable B holds 0, then −

The following table shows all the logical operators supported by Go language. Assume variable A holds true and variable B holds false, then −

Bitwise operators work on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ are as follows −

Assume A = 60; and B = 13. In binary format, they will be as follows −

A = 0011 1100

B = 0000 1101

-----------------

A&B = 0000 1100

A|B = 0011 1101

A^B = 0011 0001

~A  = 1100 0011

The Bitwise operators supported by C language are listed in the following table. Assume variable A holds 60 and variable B holds 13, then −

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

There are a few other important operators supported by Go Language including sizeof and ?:.

Operators Precedence in Go

Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator.

For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.

Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

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 🔗 .

The ternary operator in Golang

In most of the programming languages, there is an operator (?:) called ternary operator which evaluates like an if-else chain will do. But, Go does not have a ternary operator . In this post, we will dive into why it is absent in Go.

What is the ternary operator?

The ternary operator is the ?: operator used for the conditional value. Here is an example of how one would use it in code.

This operator is absent in Golang.

Why is it absent in Go?

The reason is a simple design choice. The operator although once understood, is an easy one is in fact a complicated construct for someone who is new to code. The Go programming language chose the simple approach of if-else. This is a longer version of the operator, but it is more readable .

The solution

The solution is obviously an if-else block. It represents the same code in a much cleaner way. Here is a simple if-else block representing the above expression.

The solution is verbose but it is a design choice made by the Go creators. One of the reasons being overuse and abuse of that operator to create extremely complex code that is hard to read. This decision improves over it and forces a cleaner and readable approach over that.

IMAGES

  1. Golang Variables Declaration, Assignment and Scope Tutorial

    golang assignment operator

  2. Golang Tutorial #6

    golang assignment operator

  3. Golang Operators

    golang assignment operator

  4. Tutorial 9

    golang assignment operator

  5. golang

    golang assignment operator

  6. [Golang] Using Operator On Gin Golang

    golang assignment operator

VIDEO

  1. Assignment Operator & Comparison Operator in Javascript

  2. Tutorial # 17 Assignment Operators

  3. Core

  4. #20. Assignment Operators in Java

  5. Golang backend assignment Demo

  6. Golang Basic Condition&Operator[WEBDER.Nargor]#3

COMMENTS

  1. 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 ] "=" .

  2. 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)}

  3. Difference between := and = operators in Go

    Because, := introduces "a new variable", hence using it twice does not redeclare a second variable, so it's illegal. ★ 3rd Rule: You can use them for multi-variable declarations and assignments: ★ 4th Rule (Redeclaration): You can use them twice in "multi-variable" declarations, if one of the variables is new:

  4. The Go Programming Language Specification

    The multi-valued assignment form of the receive operator reports whether a received value was sent before the channel was closed. A single channel may be used in send statements , receive operations , and calls to the built-in functions cap and len by any number of goroutines without further synchronization.

  5. 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.

  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. 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 =.

  8. 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.

  9. 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 .

  10. 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.

  11. 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.

  12. 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

  13. 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 ...

  14. 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...

  15. 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.

  16. 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 ...

  17. Go

    Go - Operators. An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. Go language is rich in built-in operators and provides the following types of operators −. This tutorial explains arithmetic, relational, logical, bitwise, assignment, and other operators one by one.

  18. 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)

  19. The ternary operator in Golang

    The reason is a simple design choice. The operator although once understood, is an easy one is in fact a complicated construct for someone who is new to code. The Go programming language chose the simple approach of if-else. This is a longer version of the operator, but it is more readable. The solution. The solution is obviously an if-else block.

  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. go

    12. One possible way to do this in just one line by using a map, simple I am checking whether a > b if it is true I am assigning c to a otherwise b. c := map[bool]int{true: a, false: b}[a > b] However, this looks amazing but in some cases it might NOT be the perfect solution because of evaluation order.