SoFunction
Updated on 2025-03-05

Detailed explanation of operators and control structures for learning Go language

Operators

The function of the operator is to combine operands into expressions. For example, in the following code, we form two expressions through assignment and plus sign:

var i,j = 1,2
n := i + j

Go operators are generally divided into six types: arithmetic operators, relational operators, logical operators, bit operators, assignment operators and pointer operators.

Arithmetic operators

Operators meaning
+ Plus sign, in addition to being used for integers, floating point numbers, and complex numbers, can also be used for string stitching.
- minus sign
* Multiply
/ Decomposition
% Find the remaining number, only used for integers
++ Self-increasing
-- Self-decreasing
+ Positive number, pay attention to the difference between the plus sign (+)
- Negative number, pay attention to the difference between minus sign (-)

Usage example:

var str1 string = "hello"
var str2 string = "world"
str := str1 + str2 //Use + sign to splice string
i := 3.2 % 2 // Report an error, you can only find the remaining number for the integer
var n int = 1
n++ 
++n //Error, self-increase can only add operands, and self-increase is the same as self-increase

Relational operators

The expression composed of logical operators is calculated as a Boolean value, which is generally used to control the conditional part of the structure:

Operators meaning
== equal
!= Not equal
<= Less than or equal to
< Less than
>= Greater than or equal to

Usage example:

if 2 == (1 + 1) {
	("equal")
}

Logical operators

The expression composed of logical operators has the same calculation result as Boolean, so it is also used to control the conditional part of the structure:

Operators meaning
&& Logic and
|| Logical or
! Logical non-unit operator, with higher priority

bit operator

Bit operators can only be used for integers

Operators meaning
& Bitwise and, both operands have 1 position 1, no
| bitwise or, both operands have a position of 1, otherwise it will be 0.
Bitwise XOR, both operands are the same as 0, otherwise it is 1
<< Move left by bit
>> Move right by bit
&^ Clear bitwise, and set the corresponding position on the left to 0 according to the position where the operand on the right is 1.

Usage example:

(2 &amp; 1) // 00000010 & 00000001, it can be seen that there is no position where both operations are 1, so the result is: 00000000(2 | 1) // 00000010 & 00000001, the result is 00000011, which is 3(2 ^ 1) // 00000010 & 00000001, the result is 00000011, which is 3
(1 &lt;&lt; 1) //00000001 =&gt; 00000010 
(2 &gt;&gt; 1) //00000010 =&gt; 00000001

(23 &amp;^ 5) 00010111 &amp;^ 00000101 =&gt; 00010010 

Assignment operator

Operators meaning
= := Assignment
+= First add the operands on the left and right, and then assign the value to the variable on the left.
-= First subtract the operands on the left and right, and then assign the value to the variable on the left.
*= First multiply the operand on the left and the right, and then assign the value to the variable on the left.
/= First divide the operands on the left and right, and then assign the value to the variable on the left.
%= First calculate the operands on the left and right, and then assign the value to the variable on the left.
<<= First, shift the operand on the left to the left according to the operand on the right, and then assign the displacement result to the variable on the left
>>= First, shift the operand on the left to the right according to the operand on the right, and then assign the displacement result to the variable on the left
&= First, calculate the operands on the left and right, and then assign the calculation result to the variable on the left.
!= First, bitwise or calculation of operands on the left and right, and then assign the calculation result to the variable on the left
^= First calculate the operands on the left and right side by XOR, and then assign the calculation result to the variable on the left.

Pointer operator

Operators meaning
& Get the address of the variable in memory
* Declare pointer variables

Operator priority

Go's ++ and -- operators form expressions when they act on operands, so they are not included in the operator's priority.

In Go, unary operators have higher priority, such as +(positive number), -(negative number), !(negative), *(pointer declaration), &(address).

The assignment operator has the lowest priority. In addition to the unary operator and the assignment operator, the remaining operators can be divided into five priority levels:

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

Control structure

Go's control structure includesifStatement,forStatements andswitchThere are three types of sentences.

If

ifThe statement is used to determine whether a certain condition is satisfied. If it is satisfied, the code block in the if statement is executed. If it is not satisfied, the code is ignored.ifThe code block in the statement and continue to be executed backwards.

The easiestifThe statement structure is:

if boolean expression {
	// do something	
}

inboolean expressionIt is an expression that can obtain a Boolean value, when the Boolean value istrue, will executeifThe code blocks in the statement, such as:

if 2 < 10 {
	("ok")
}

Except for judgmentboolean expressionoutside,ifIt can also contain an initialization expression:

if initialization;boolean expression{
	// do something	
}

In this case,ifThe initialization expression will be executed first, and then the judgment will be made.boolean expressionIs the obtained boolean?true

if i = 10;i < 100 {
	("ok")
}

ifYou can also follow the statementelseStatement, of courseifWhen the conditions are not met, they will be executedelseCode blocks in statements:

if boolean expression{
	// do something	
}else{
	// do something	
}

Usage example:

if i = 11;i < 11{
	("ok")
}else{
	("bad")
}

If there are multiple branch conditions, you canifFollow multiple else if statements after the statement, and you can follow it at the endelseStatement, when all conditions are not met, will be executedelseCode blocks in statements:

if boolean expression1 {
	// do something	
} else if boolean expression2 {
	// do something else	
} else if boolean expression3 {
	// do something else	
}else {
	// catch-all or default
}

For

forStatements are used to execute blocks of code according to conditional loops, the simplestforThe statement format is as follows:

for condition {
	//do something
}

conditionis an expression that can obtain a Boolean value.GoThere is no languagewhileordo-whilestatements, so the usage of this method is close to that of other programming languageswhileordo-whileStatement:

x := 1
for x < 20{
	(x)
	x++
}

ifconditionis empty, then at this timeforThis is a dead loop:

for {
	//do something
}

forThe most classic, some usages in other programming languages ​​are the following form:

for init statement;condition;post statement{
	//do something
}

Usage example:

for i := 0; i< 10 ;i++ {
	(i)
}

in addition,forStatements and keywordsrangeCoordinate, it can be used to traverse arrays,mapIts functions are similar to slices, etc.PHPIn-houseforeachStatement:

for k,v := range array {
	//do something
}

Usage example:

var a [10]int = [10]int{1,2,3,4,5,6,7,8,9,10}

for index,value := range a {
	(index,value)
}

usebreakKeyword end loop

for i := 0; i < 10; i++ {
	if i == 5 {
		break
	}
	(i)
}

usecontinueEnd to skip a single loop:

for i := 0;i<10;i++{
	if i == 5 {
		continue
	}
	(i)
}

Switch

SwitchSimilar to if, it is used to execute code blocks that meet the conditions according to the condition, but its usage isifdifferent,switchThere are several different usages:

The first method will compare the value after switch with the value followed by case, and if the condition is met, it will be executedcaseIf none of the code blocks in it are satisfied, then executedefaultThe code block in it, its structure is as follows:

switch var1 {
	case val1:
		...
	case val2:
		...
	default:
		...
}

Usage example:

var x = 8
switch x {
	case 8 :
		("8")
	case 9 :
	  ("9")
	case 10 :
	  ("10")
	default :
		("not found")
}

From the example above, we can see that after a certain condition is met, the switch statement will be exited after the switch is executed, and it does not need to be used like other programming languagesbreakCome and exitswitchStatement.

If you do not want to exit the switch statement, you need to continue to execute the switch statement.caseUse within a statementfallthroughKeywords:

var x = 8
switch x {
	case 8 :
		("8")
		fallthrough
	case 9 :
	  ("9")
	  fallthrough
	case 10 :
	  ("10")
	default :
		("not found")
}

The above statement is matchingcase 8:Afterwards, I encounteredfallthroughstatement, so continue to execute, and then continue to touchfallthroughThe statement continues to be executed, so all three case code blocks will be executed.

switchAnother way to use is to omit the subsequent variables and place the execution judgment conditionscaseAfter the keyword, this usage isif/elseifThe statement is similar:

switch {
	case condition1:
		...
	case condition2:
		...
	default:
		...
}

Usage example:

x := 10
switch {
	case x >= 10:
		("10")
	case x > 11:
		("11")
	default:
		("not found")
}

switchAn initialization statement can be followed:

switch initialization {
	case condition1:
		...
	case condition2:
		...
	default:
		...
}

Usage example:

switch x := 10; {
	case x >= 10:
		("10")
	case x > 11:
		("11")
	default:
		("not found")
}

type-switchyesswitchAnother usage of statements is mainly used for type assertions, and subsequently learn interfaces (interface) Introduction

summary

To sum up, this article mainly talks about three points:

Supported operators:

  • Arithmetic operators
  • Relational operators
  • Logical operators
  • Assignment operator
  • bit operator
  • Pointer operator

2. Optimization level of operators

Supported control structures:

  • If statement
  • For statement
  • Switch statement

This is the article about the detailed explanation of operators and control structures of Go language. For more related Go language operators and control structures, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!