1. If...else judgment syntax
There is no difference between the use of grammar and other languages.
The sample code is as follows:
// Judgment statementfunc panduan(a int) { if a > 50 { ("a > 50") } else if a < 30 { ("a < 30") } else { ("a <= 50 and a >= 30") } } func main() { panduan(120) }
Execution results
a > 50
2. If nesting syntax
The sample code is as follows
//Nested judgmentfunc qiantao(b, c uint) { if b >= 100 { b -= 20 if c > b { ("c OK") } else { ("b OK") } } }
Execution results
c OK
3. Switch statement
There are two ways to write, no break is required.
The sample code is as follows
//Use switchfunc test_switch() { var a uint = 90 var result string switch a { case 90: result = "A" case 80, 70, 60: result = "B" default: result = "C" } ("result: %v\n", result) switch { case a > 90: result = "A" case a <= 90 && a >= 80: result = "B" default: result = "C" } ("result: %v\n", result) }
Execution results
result: A
result: B
Notice
1. However, add variables after switch, and the case afterwards mainly makes matching judgments. You can also use switch{} directly to directly match the relationship operation results.
2. You can choose to match multiple items in case.
4. Type switch statement
The switch statement can use type-switch for type judgment, which feels very practical syntax.
The sample code is as follows
//Test type switchfunc test_type_switch() { var x interface{} x = 1.0 switch i := x.(type) { case nil: ("x type = %T\n", i) case bool, string: ("x type = bool or string\n") case int: ("x type = int\n") case float64: ("x type = float64\n") default: ("Unknown\n") } }
Execution results
x type = float64
Notice
1. Interface{} can represent any type.
2. Syntax format variables. (type)
5. Use of fallthrough keywords
Using the fallthrough keyword will force the content of the subsequent case statement, and the case condition will be triggered no matter whenever it is.
The sample code is as follows
// Test fallthroughfunc test_fallthrough() { a := 1 switch { case a < 0: ("1") fallthrough case a > 0: ("2") fallthrough case a < 0: ("3") fallthrough case a < 0: ("4") case a > 0: ("5") fallthrough case a < 0: ("6") fallthrough default: ("7") } }
Execution results
2
3
4
Notice
1. If fallthrough does not exist in the case execution downward execution, the case execution will be stopped.
summary
I saw that there is another select statement that needs to be used in conjunction with the chan keyword. I don’t know about it. Let’s study the chan keyword later.
This is the article about the detailed explanation of the use of conditional statements for Go language learning. For more relevant Go conditional statement content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!