iT邦幫忙

2021 iThome 鐵人賽

DAY 5
0
DevOps

"GoDevOps": Learn DevOps Tools with Go系列 第 5

[Golang] Introduction to Control Flow

If statement

if (condition1) {

} else if (condition2) {

} else {

}

Note that, the parentheses () can be omitted from an if statement. for example:

package main

import "fmt"

func main() {
	var x = 7
	if num%3 == 0 && num%5 == 0 {
		fmt.Printf("%d is divisible by both 3 and 5\n", x)
	} else if x < 0 {
		fmt.Printf("%d is negative\n", x)
	} else {
		fmt.Printf("%d is positive\n", x)
	}
}

Switch statement

Switch evaluates all the cases from top to bottom until a case succeeds. Once a case succeeds, it runs the block of code specified in that case and then stops the evaluation.

package main

import "fmt"

func main() {
	code := "AT"
	switch code {
	case "TW", "ROC":
		fmt.Println("Taiwan")
	case "AU":
		fmt.Println("Australia")
	case "AT":
		{
			fmt.Println("Austria")
			fmt.Println("There is no kangaroos in Austria")
		}
	default:
		fmt.Println("Other Country")
	}
}

For loop

You can use continue statement to skip running the loop body midway and continue to the next iteration of the loop.
The break statement can be used to stop a loop before its normal termination.

package main

import "fmt"

func main() {
	for i := 100; i < 150; i++ {
		if i%2 == 0 {
			continue
		} else if i%7 == 0 {
			fmt.Printf("%d is a the first multiple of 7\n", i)
			break
		}
		fmt.Printf("%d is a the odd number\n", i)
	}
}

上一篇
[Golang] Introduction to Variables
下一篇
[Golang] Array and Slice
系列文
"GoDevOps": Learn DevOps Tools with Go11
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言