Golang Learning Note -1.7 If-else statement

Source: Internet
Author: User
Tags variable scope

This is the seventh chapter of Golang Language Learning Tutorial

If-else

ifis 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 ifStatements 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 == 0Used 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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.