This is a creation in Article, where the information may have evolved or changed.
Original: https://golangbot.com/if-statement/
This is the eighth chapter of this Golang series of tutorials.
if is a conditional statement. The syntax for the IF statement is:
if condition { }
If condition true So, then execute { } the code between and.
Unlike other languages (such as C), it {} is required even if there is only one statement between the two {} .
ifStatements can be followed by optional else if and else statements:
if condition { elseifelse {}
ifYou can then follow any number of else if statements. conditionThe evaluation is carried out from top to bottom, until the if else if condition corresponding code block is executed until one or the other true . If there is not one conditon true , then the else code block is executed.
Let's write a simple procedure to determine whether a number is odd or even:
package mainimport ( "fmt")func main() { num := 10 if num % 2 == 0//checks if number is even fmt.Println("the number is even") } else { fmt.Println("the number is odd") }}
if num % 2 == 0This statement detects 2 whether the remainder of a number is divided by 0 , if it is, the output: "the number is even" , otherwise output: "the number is odd" . The above program output: the number is even .
ifThe statement also has the following variants. This form of if statement is executed first and statement then judged conditon .
if statement; condition { }
Let's rewrite the above program in this form if :
package mainimport ( "fmt")func main() { if num := 10; num % 2 == 0//checks if number is even fmt.Println(num,"is even") } else { fmt.Println(num,"is odd") }}
In the above program, num initialize in the if statement. One thing to note is that num access can only be if made in and else inside, i.e. num the scope is limited to if else blocks. If we try to if else access it or not num , the compiler will make an error.
Let's else if write another program:
package Mainimport ( "FMT" ) func main () {num: = if num >= 0 && num <= {fmt. Println ( "number is greater than" )} else if num >= * && num <= {fmt. Println ( "number is between and" )} else { Fmt. Println ( "number is greater than" )}}
The above program else if num >= 51 && num <= 100 is true , so the output of the program is: number is between 51 and 100 .
This concludes the introduction of the IF Else statement. Thanks for reading.
Directory
Previous post: Golang Tutorial: (vii) package
Next: Golang Tutorial: (ix) Looping statements