Condition

The if statement verifies a binary condition and executes the code inside the if block when the condition is true. When an else block is present, it's executed when the condition is false. This statement also allows a short declaration before the condition, separated by a ;. This condition can be chained with an else if statement, as shown in the following code:

if r := a%10; r != 0 { // if with short declaration
if r > 5 { // if without declaration
a -= r
} else if r < 5 { // else if statement
a += 10 - r
}
} else { // else statement
a /= 10
}

The other condition statement is switch. This allows a short declaration, like if, and this is followed by an expression. The value of such an expression can be of any type (not just Boolean), and it's evaluated against a series of case statements, each one followed by a block of code. The first statement that matches the expression, if the switch and case condition are equal, has its block executed.

If a break statement is present in the case where the block execution is interrupted, but  there's a fallthrough, the code inside the following case block is executed. A special case called default can be used to execute its code if no case is satisfied, as shown in the following code:

switch tier {                        // switch statement
case 1: // case statement
fmt.Println("T-shirt")
if age < 18{
break // exits the switch block
}
fallthrough // executes the next case
case 2:
fmt.Println("Mug")
fallthrough // executes the next case
case 3:
fmt.Println("Sticker pack")
default: // executed if no case is satisfied
fmt.Println("no reward")
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.23.147