search
HomeBackend DevelopmentGolangAn article to help you understand the basic operators and flow control of Go language

This time we continue to learn the basic operators and process control of Go.

Operator

The name operator sounds mysterious, but in fact we see it a lot more often, like =, ,/some type of.

Operators are mainly divided into

  • arithmetic operators

  • Relational operators

  • Logical operators

  • Bit operator

  • Assignment operator

The following is simple Learn about the following.


Arithmetic operators

##As the name suggests, arithmetic operators are mainly used in arithmetic, such as addition, subtraction, multiplication and division

Briefly understand the following.


Relational operators

Operator ##Description
##Add
- subtraction
* Multiply
/ Division
#% Look for remainder
自add
##-- 自decrement
##!= Check whether the two values ​​​​are not equal, return True if they are not equal, otherwise return False>Check whether the value on the left is greater than the value on the right, if so return True otherwise return False


Logical operators

##Operators Description
##== Check whether the two values ​​are equal, return True if they are equal, otherwise return False
>= Check whether the value on the left is greater than or equal to the value on the right, if so Returns True otherwise returns False
## Check Whether the value on the left is less than the value on the right, if so return True otherwise return False
## Check whether the value on the left is less than or equal to the value on the right, if so return True otherwise return False
##!Logical NOT operator. False if the condition is True, True otherwise

Note: Logical operators are very important and are often used in development.


Bit operators

Bit operators have some low-level functions and are used in special cases.

##Operators describe
&& Logical and operator. If both operands are True, it is True, otherwise it is False
##|| Logical or operator. If the operands on both sides have a True, it is True, otherwise it is False
##The two numbers involved in the operation correspond to Carry AND. (It is 1 if both are 1) |The binary OR corresponding to each of the two numbers involved in the operation. (If one of the two bits is 1, it is 1) ##^


Assignment Operator

The assignment operator is also commonly used in development.

Operator ##Description
##&
The corresponding binary bits of the two numbers participating in the operation are exclusive or. When the two corresponding binary bits are different, the result is 1.(If the two numbers are different, it is 1)
##Shifting n bits to the left is multiplying by 2 raised to the nth power. "a
##>> Shift right by n bits That's divided by 2 to the nth power. "a>>b" shifts all binary bits of a to the right by b bits.
##*=##>>=Assign value after right shift&=|


Process control

In Go, there are the following types of process control.

  • if

    • ##if

    • switch case

  • for

    • Standard for

    • ##forrange

    ##goto(Use with caution )

##if

Syntax

//方式一,一个if
if 条件{
    //执行语句
}
//方式二,if条件不成功执行else
if 条件{
    //if成功语句
}else{
    //if不成功语句
}
//方式三,带有else if得
if 条件1{
    //if成功语句
}else if 条件2{
    //if不成功,继续else if条件
}else{
    //上面都不成功,执行else
}

Example

package main

import "fmt"

func main() {
    var gender = "男"

    if gender == "男" {
        fmt.Println("男")
    } else if gender == "女" {
        fmt.Println("女")
    } else {
        fmt.Println("啥都不是???")
  }
}


switch case

switch caseif本质是一个东西,但是在某些场景,switch是比if更加简洁的。

代码

package main

import "fmt"

func main() {
    var week = 3
    switch week {
    case 1:
        fmt.Println("周一")
    case 2:
        fmt.Println("周二")
    case 3:
        fmt.Println("周三")
    case 4:
        fmt.Println("周四")
    case 5:
        fmt.Println("周五")
    case 6:
        fmt.Println("周六")
    case 7:
        fmt.Println("周日")
    default://如果上面都没执行,会执行default
        fmt.Println("星期八????")
  }
}

注:在Go中,switch是没有case穿透的。


Go的switch可以case多个值。

package main

import "fmt"

func main() {
    var week = 3
    switch week {
    case 1, 2, 3, 4, 5:
        fmt.Println("上班")
    case 6:
        fmt.Println("周六睡懒觉")
    case 7:
        fmt.Println("周日去旅游")
    default:
        fmt.Println("飞天了???")
  }
}


for

标准for循环

语法

for 初始条件;判断条件;结束条件{
    语句
}

代码

package main

import "fmt"

func main() {
    for i := 0; i < 10; i++ {
        fmt.Println(i)
  }
}

无限循环

谨慎执行!!!

package main

import "fmt"

func main() {
    for{
        fmt.Println("666")
  }
}

for range

for ragne可以很方便循环数组,切片,字符串,map,channel等。

遍历数组示例

package main

import "fmt"

func main() {
    var student_list = [...]string{"张三", "李四", "王五"}
    for index, v := range student_list {
        //index为下标,v是每一个的值
        fmt.Println(index, v)
  }
}

注:

如果数组,切片,字符串
  index是下标,v是值
如果是map
  index是键,v是对(值)
如果是通道
  只有一个值,就是通道内的值

补充:

在Go中,只有for循环,没有while。

for循环就两种方式。


goto

goto可以通过标签在代码间无条件跳转,这就造成了一个局面,如果使用gote过多,会造成逻辑混乱,跳来跳去。

所以,在开发中,要慎用,不到万不得已,不要使用。


示例

package main

import "fmt"

func main() {
  for i := 0; i < 10; i++ {
    for j := 0; j < 10; j++ {
      if j == 2 {
        // 直接跳转到下面的 breakTag 标签
        goto breakTag
      }
      fmt.Printf("%v-%v\n", i, j)
    }
  }
  //要跳转的标签
breakTag:
  fmt.Println("结束for循环")
  }


Operator ##Description
= Simple assignment operator, converts an expression Assign the value of the formula to an lvalue
= Assign the value after addition
##-= After subtracting, assign the value
## Multiply and then assign value
/= ##Divide and then assign the value
%= ##Find the remainder and then assign the value
Assign value after left shift
##Assignment after bitwise AND
= Assignment after bitwise OR
##^= Assignment after bitwise XOR

The above is the detailed content of An article to help you understand the basic operators and flow control of Go language. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:Go语言进阶学习. If there is any infringement, please contact admin@php.cn delete
The Performance Race: Golang vs. CThe Performance Race: Golang vs. CApr 16, 2025 am 12:07 AM

Golang and C each have their own advantages in performance competitions: 1) Golang is suitable for high concurrency and rapid development, and 2) C provides higher performance and fine-grained control. The selection should be based on project requirements and team technology stack.

Golang vs. C  : Code Examples and Performance AnalysisGolang vs. C : Code Examples and Performance AnalysisApr 15, 2025 am 12:03 AM

Golang is suitable for rapid development and concurrent programming, while C is more suitable for projects that require extreme performance and underlying control. 1) Golang's concurrency model simplifies concurrency programming through goroutine and channel. 2) C's template programming provides generic code and performance optimization. 3) Golang's garbage collection is convenient but may affect performance. C's memory management is complex but the control is fine.

Golang's Impact: Speed, Efficiency, and SimplicityGolang's Impact: Speed, Efficiency, and SimplicityApr 14, 2025 am 12:11 AM

Goimpactsdevelopmentpositivelythroughspeed,efficiency,andsimplicity.1)Speed:Gocompilesquicklyandrunsefficiently,idealforlargeprojects.2)Efficiency:Itscomprehensivestandardlibraryreducesexternaldependencies,enhancingdevelopmentefficiency.3)Simplicity:

C   and Golang: When Performance is CrucialC and Golang: When Performance is CrucialApr 13, 2025 am 12:11 AM

C is more suitable for scenarios where direct control of hardware resources and high performance optimization is required, while Golang is more suitable for scenarios where rapid development and high concurrency processing are required. 1.C's advantage lies in its close to hardware characteristics and high optimization capabilities, which are suitable for high-performance needs such as game development. 2.Golang's advantage lies in its concise syntax and natural concurrency support, which is suitable for high concurrency service development.

Golang in Action: Real-World Examples and ApplicationsGolang in Action: Real-World Examples and ApplicationsApr 12, 2025 am 12:11 AM

Golang excels in practical applications and is known for its simplicity, efficiency and concurrency. 1) Concurrent programming is implemented through Goroutines and Channels, 2) Flexible code is written using interfaces and polymorphisms, 3) Simplify network programming with net/http packages, 4) Build efficient concurrent crawlers, 5) Debugging and optimizing through tools and best practices.

Golang: The Go Programming Language ExplainedGolang: The Go Programming Language ExplainedApr 10, 2025 am 11:18 AM

The core features of Go include garbage collection, static linking and concurrency support. 1. The concurrency model of Go language realizes efficient concurrent programming through goroutine and channel. 2. Interfaces and polymorphisms are implemented through interface methods, so that different types can be processed in a unified manner. 3. The basic usage demonstrates the efficiency of function definition and call. 4. In advanced usage, slices provide powerful functions of dynamic resizing. 5. Common errors such as race conditions can be detected and resolved through getest-race. 6. Performance optimization Reuse objects through sync.Pool to reduce garbage collection pressure.

Golang's Purpose: Building Efficient and Scalable SystemsGolang's Purpose: Building Efficient and Scalable SystemsApr 09, 2025 pm 05:17 PM

Go language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.

Why do the results of ORDER BY statements in SQL sorting sometimes seem random?Why do the results of ORDER BY statements in SQL sorting sometimes seem random?Apr 02, 2025 pm 05:24 PM

Confused about the sorting of SQL query results. In the process of learning SQL, you often encounter some confusing problems. Recently, the author is reading "MICK-SQL Basics"...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.