Go - if...else 語句
if 語句可以後跟一個可選的 else 語句,當布林表示式為假時執行該語句。
語法
在 Go 程式語言中,if...else 語句的語法為 -
if(boolean_expression) {
/* statement(s) will execute if the boolean expression is true */
} else {
/* statement(s) will execute if the boolean expression is false */
}
如果布林表示式求值為 true,那麼將執行if 程式碼塊,否則將執行else 程式碼塊。
流程圖
示例
package main
import "fmt"
func main() {
/* local variable definition */
var a int = 100;
/* check the boolean condition */
if( a < 20 ) {
/* if condition is true then print the following */
fmt.Printf("a is less than 20\n" );
} else {
/* if condition is false then print the following */
fmt.Printf("a is not less than 20\n" );
}
fmt.Printf("value of a is : %d\n", a);
}
編譯並執行以上程式碼後,將生成以下結果 -
a is not less than 20; value of a is : 100
if...else if...else 語句
if 語句可以後跟一個可選的 else if...else 語句,這對於使用一個 if...else if 語句測試各種條件非常有用。
在使用 if、else if 和 else 語句時,有幾點需要注意 -
一個 if 可以有 0 個或 1 個 else,並且它必須放在任何 else if 之後。
一個 if 可以有 0 到多個 else if,並且它們必須放在 else 之前。
一旦一個 else if 執行成功,就不會測試剩餘的任何 else if 或 else。
語法
在 Go 程式語言中,if...else if...else 語句的語法為 -
if(boolean_expression 1) {
/* Executes when the boolean expression 1 is true */
} else if( boolean_expression 2) {
/* Executes when the boolean expression 2 is true */
} else if( boolean_expression 3) {
/* Executes when the boolean expression 3 is true */
} else {
/* executes when the none of the above condition is true */
}
示例
package main
import "fmt"
func main() {
/* local variable definition */
var a int = 100
/* check the boolean condition */
if( a == 10 ) {
/* if condition is true then print the following */
fmt.Printf("Value of a is 10\n" )
} else if( a == 20 ) {
/* if else if condition is true */
fmt.Printf("Value of a is 20\n" )
} else if( a == 30 ) {
/* if else if condition is true */
fmt.Printf("Value of a is 30\n" )
} else {
/* if none of the conditions is true */
fmt.Printf("None of the values is matching\n" )
}
fmt.Printf("Exact value of a is: %d\n", a )
}
編譯並執行以上程式碼後,將生成以下結果 -
None of the values is matching Exact value of a is: 100
go_decision_making.htm
廣告