search
HomeBackend DevelopmentGolangLearn to use conditionals and loop statements in Golang

Learn to use conditionals and loop statements in Golang

Dec 23, 2023 pm 01:19 PM
golangConditional statementsloop statement

Learn to use conditionals and loop statements in Golang

To master conditional statements and loop statements in Golang, you need specific code examples

In Golang, conditional statements and loop statements are a very important part of the program. Conditional statements are used to determine the execution flow of the program, while loop statements are used to repeatedly execute a section of code. This article will introduce conditional statements and loop statements in Golang in detail and provide specific code examples.

  1. Conditional statements

Conditional statements are used to execute different code blocks based on whether the condition is true or false. In Golang, conditional statements include if statements, if-else statements and switch statements.

1.1. if statement

The if statement is used to execute the code block under the specified condition. If the condition is true, the code block after the if is executed. The sample code is as follows:

package main

import "fmt"

func main() {
    age := 18

    if age >= 18 {
        fmt.Println("你已经成年了")
    }
}

In the above code, if the value of age is greater than or equal to 18, then "You are an adult" is output. Otherwise, no action is performed.

1.2. if-else statement

The if-else statement is used to execute different blocks of code when the condition is true and when the condition is false. The sample code is as follows:

package main

import "fmt"

func main() {
    age := 17

    if age >= 18 {
        fmt.Println("你已经成年了")
    } else {
        fmt.Println("你还未成年")
    }
}

In the above code, if the value of age is greater than or equal to 18, then output "You are an adult"; otherwise, output "You are not yet a minor".

1.3. switch statement

The switch statement is used to select different code blocks for execution based on the value of the expression. The sample code is as follows:

package main

import "fmt"

func main() {
    fruit := "apple"

    switch fruit {
    case "apple":
        fmt.Println("这是一个苹果")
    case "banana":
        fmt.Println("这是一个香蕉")
    default:
        fmt.Println("这不是水果")
    }
}

In the above code, select different code blocks to output based on the value of fruit. If the value of fruit is "apple", then output "This is an apple"; if the value of fruit is "banana", then output "This is a banana"; otherwise, Output "This is not a fruit".

  1. Loop statement

Loop statement is used to repeatedly execute a section of code until a specific condition is met. In Golang, loop statements include for loops and range loops.

2.1. for loop

The for loop is used to repeatedly execute a piece of code until a specific condition is met. The sample code is as follows:

package main

import "fmt"

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

In the above code, use a for loop to output numbers from 0 to 4.

2.2. Range loop

The range loop is used to iterate over the elements in an array, slice, map, or channel. The sample code is as follows:

package main

import "fmt"

func main() {
    nums := []int{1, 2, 3, 4, 5}

    for index, value := range nums {
        fmt.Println("索引:", index, "值:", value)
    }
}

In the above code, use the range loop to traverse the nums slice and output the index and value of each element.

Through the code examples in this article, I believe that readers have mastered the basic usage of conditional statements and loop statements in Golang. When actually writing code, conditional statements and loop statements are very commonly used and can help us implement complex logic and repeated operations. Therefore, proficiency in these statements will play an important role in improving programming abilities.

The above is the detailed content of Learn to use conditionals and loop statements in Golang. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Golang vs. Python: The Pros and ConsGolang vs. Python: The Pros and ConsApr 21, 2025 am 12:17 AM

Golangisidealforbuildingscalablesystemsduetoitsefficiencyandconcurrency,whilePythonexcelsinquickscriptinganddataanalysisduetoitssimplicityandvastecosystem.Golang'sdesignencouragesclean,readablecodeanditsgoroutinesenableefficientconcurrentoperations,t

Golang and C  : Concurrency vs. Raw SpeedGolang and C : Concurrency vs. Raw SpeedApr 21, 2025 am 12:16 AM

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Why Use Golang? Benefits and Advantages ExplainedWhy Use Golang? Benefits and Advantages ExplainedApr 21, 2025 am 12:15 AM

Reasons for choosing Golang include: 1) high concurrency performance, 2) static type system, 3) garbage collection mechanism, 4) rich standard libraries and ecosystems, which make it an ideal choice for developing efficient and reliable software.

Golang vs. C  : Performance and Speed ComparisonGolang vs. C : Performance and Speed ComparisonApr 21, 2025 am 12:13 AM

Golang is suitable for rapid development and concurrent scenarios, and C is suitable for scenarios where extreme performance and low-level control are required. 1) Golang improves performance through garbage collection and concurrency mechanisms, and is suitable for high-concurrency Web service development. 2) C achieves the ultimate performance through manual memory management and compiler optimization, and is suitable for embedded system development.

Is Golang Faster Than C  ? Exploring the LimitsIs Golang Faster Than C ? Exploring the LimitsApr 20, 2025 am 12:19 AM

Golang performs better in compilation time and concurrent processing, while C has more advantages in running speed and memory management. 1.Golang has fast compilation speed and is suitable for rapid development. 2.C runs fast and is suitable for performance-critical applications. 3. Golang is simple and efficient in concurrent processing, suitable for concurrent programming. 4.C Manual memory management provides higher performance, but increases development complexity.

Golang: From Web Services to System ProgrammingGolang: From Web Services to System ProgrammingApr 20, 2025 am 12:18 AM

Golang's application in web services and system programming is mainly reflected in its simplicity, efficiency and concurrency. 1) In web services, Golang supports the creation of high-performance web applications and APIs through powerful HTTP libraries and concurrent processing capabilities. 2) In system programming, Golang uses features close to hardware and compatibility with C language to be suitable for operating system development and embedded systems.

Golang vs. C  : Benchmarks and Real-World PerformanceGolang vs. C : Benchmarks and Real-World PerformanceApr 20, 2025 am 12:18 AM

Golang and C have their own advantages and disadvantages in performance comparison: 1. Golang is suitable for high concurrency and rapid development, but garbage collection may affect performance; 2.C provides higher performance and hardware control, but has high development complexity. When making a choice, you need to consider project requirements and team skills in a comprehensive way.

Golang vs. Python: A Comparative AnalysisGolang vs. Python: A Comparative AnalysisApr 20, 2025 am 12:17 AM

Golang is suitable for high-performance and concurrent programming scenarios, while Python is suitable for rapid development and data processing. 1.Golang emphasizes simplicity and efficiency, and is suitable for back-end services and microservices. 2. Python is known for its concise syntax and rich libraries, suitable for data science and machine learning.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment