This is the seventh chapter of Golang Language Learning Tutorial
If-else
if
is a conditional statement
The syntax is as follows:
if condition { }
If condition
true, the {}
code between execution
Go also has optional else if
and else
statement
if condition {} else if condition {} else {}
else if
Statements can have any number, judging from top to bottom.
If the If or the else if
judgment is true, the corresponding {}
medium code is executed.
Automatic code execution if no conditions are true else
First, write a simple judgment number is an even numbered program:
package mainimport "fmt"func main(){ num := 21 if num % 2 == 0 { //如果 num 取 2 的余数为 0 fmt.Println("this number is env") //输出this number is env } else { fmt.Println("this number is odd") //若余数不为 0 ,则输出this number is env }}
if num % 2 == 0
Used to detect whether Num takes 2 of the remainder is 0.
Above program output:num 取 2 的余数为 0
If there is another form, it contains an statement
optional part that runs before the condition is judged.
The syntax is as follows:
if statement; condition { }
Rewrite a program that judges odd even numbers:
package mainimport "fmt"func main(){ if numb := 21; numb % 2 == 0 { fmt.Println("this number is env") } else { fmt.Println("this number is odd") }}
In the above procedure, if
it is assigned a value in the condition, so the variable scope assigned in the condition numb
can only be in this block of if
code. If you try to if
access it from outside or else
, the numb
compiler does not pass.
Attention:
Else must be after the IF statement}, otherwise the error will be
The conditional statement also has a switch
statement, and the next section learns the switch
statement.
Above for learning Golang If-else article