go by example switch statement
Go's switch statement does not require break and automatically terminates by default. It supports any type comparison, expression omission, multi-value matching and type judgment. 1. The basic switch matches branches according to the value and outputs Regular day; 2. Use fallthrough to penetrate and execute the next branch, output Match a and Match b; 3. No-expression switch can realize conditional judgments similar to if-else, output Adult; 4. Type switch judges the interface type through v := x.(type), output String: hello; 5. Multi-value case allows one branch to match multiple values and output Even. Go's switch is simple and flexible, suitable for clearly expressing multi-branch logic.
In Go, switch
statements are a very clear and flexible control structure that are used to execute different code branches based on the value of a variable or expression. Go's switch
is more powerful than other languages, such as supporting any type of comparison, expression omission, multi-value matching, etc.

The following is a few common Go by Example style examples to explain the usage of switch
.
1. Basic switch statements
package main import "fmt" func main() { day := "tuesday" switch day { case "monday": fmt.Println("Start of the week") case "friday": fmt.Println("Time to relax!") case "saturday", "sunday": fmt.Println("Weekend!") default: fmt.Println("Regular day") } }
Output:

Regular day
Note: Go's
case
does not requirebreak
, and the default is automatic break (no penetration). If you want to penetrate to the next case, usefallthrough
.
2. Use fallthrough to penetrate
switch "a" { case "a": fmt.Println("Match a") Fallthrough case "b": fmt.Println("Match b") }
Output:

Match a Match b
fallthrough
will unconditionally execute the code body of the next case , even if it does not match.
3. Expression switch (no switch value)
Go supports switch
without expressions, similar to if/else if
chain:
age := 25 switch { case age < 18: fmt.Println("Minor") case age >= 18 && age < 60: fmt.Println("Adult") default: fmt.Println("Senior") }
Output:
Adult
This form is suitable for judgment of complex conditions.
4. Type switch (judgment interface type)
When you are not sure about the specific type of interface variables, you can use type switch:
var x interface{} = "hello" switch v := x.(type) { case string: fmt.Printf("String: %s\n", v) case int: fmt.Printf("Integer: %d\n", v) case nil: fmt.Println("nil") default: fmt.Printf("Unknown type: %T\n", v) }
Output:
String: hello
v
is the value after type assertion and can be used directly.
5. Multi-value cases and expressions
n := 4 switch n { case 1, 3, 5, 7, 9: fmt.Println("Odd") case 2, 4, 6, 8, 10: fmt.Println("Even") default: fmt.Println("Out of range") }
Output:
Even
Summary: Key features of Go switch
- ✅ Automatic break, no manual
- ✅ Supports any type of string, integer, boolean, interface, etc.
- ✅ The expression after switch can be omitted and becomes a conditional judgment
- ✅ Support
fallthrough
to achieve penetration - ✅ Type switch is used to handle type judgment of
interface{}
Basically that's it. Go's switch
is simple and powerful, and it is clearer than a long list of if-else
when writing conditional branches. Not complicated, but it is easy to ignore its flexibility.
The above is the detailed content of go by example switch statement. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

Python is an efficient tool to implement ETL processes. 1. Data extraction: Data can be extracted from databases, APIs, files and other sources through pandas, sqlalchemy, requests and other libraries; 2. Data conversion: Use pandas for cleaning, type conversion, association, aggregation and other operations to ensure data quality and optimize performance; 3. Data loading: Use pandas' to_sql method or cloud platform SDK to write data to the target system, pay attention to writing methods and batch processing; 4. Tool recommendations: Airflow, Dagster, Prefect are used for process scheduling and management, combining log alarms and virtual environments to improve stability and maintainability.

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

Java's garbage collection (GC) is a mechanism that automatically manages memory, which reduces the risk of memory leakage by reclaiming unreachable objects. 1.GC judges the accessibility of the object from the root object (such as stack variables, active threads, static fields, etc.), and unreachable objects are marked as garbage. 2. Based on the mark-clearing algorithm, mark all reachable objects and clear unmarked objects. 3. Adopt a generational collection strategy: the new generation (Eden, S0, S1) frequently executes MinorGC; the elderly performs less but takes longer to perform MajorGC; Metaspace stores class metadata. 4. JVM provides a variety of GC devices: SerialGC is suitable for small applications; ParallelGC improves throughput; CMS reduces

Gradleisthebetterchoiceformostnewprojectsduetoitssuperiorflexibility,performance,andmoderntoolingsupport.1.Gradle’sGroovy/KotlinDSLismoreconciseandexpressivethanMaven’sverboseXML.2.GradleoutperformsMaveninbuildspeedwithincrementalcompilation,buildcac

defer is used to perform specified operations before the function returns, such as cleaning resources; parameters are evaluated immediately when defer, and the functions are executed in the order of last-in-first-out (LIFO); 1. Multiple defers are executed in reverse order of declarations; 2. Commonly used for secure cleaning such as file closing; 3. The named return value can be modified; 4. It will be executed even if panic occurs, suitable for recovery; 5. Avoid abuse of defer in loops to prevent resource leakage; correct use can improve code security and readability.

Choosing the right HTMLinput type can improve data accuracy, enhance user experience, and improve usability. 1. Select the corresponding input types according to the data type, such as text, email, tel, number and date, which can automatically checksum and adapt to the keyboard; 2. Use HTML5 to add new types such as url, color, range and search, which can provide a more intuitive interaction method; 3. Use placeholder and required attributes to improve the efficiency and accuracy of form filling, but it should be noted that placeholder cannot replace label.
