Golang Program Flow Control EP5

Sharing is caring!

Golang ก็เหมือนภาษาอื่น ๆ คือจะมี IF, ELSE, FOR LOOPS, SWITH CASE อื่น ๆ

IF, ELSE IF, ELSE คำสั่งหากินของทุก ๆ ภาษา เกือบจะถูกเรียกว่า AI

อธิบายรวดเดียวกันไปเลย ด้วยโค๊ดข้างล่างนี้

// if condition_that_evaluates_to_boolean{
//      perform action1
// }else if condition_that_evaluates_to_boolean{
//      perform action2
// }else{
//      perform action3
// }

price, inStock := 100, true

if price >= 80 { // parenthesis are no required to enclose the testing condition
    fmt.Println("Too Expensive")
}

if price <= 100 && inStock == true { //the same with: if price <= 100 && inStock { }
    fmt.Println("Buy it!")
}

// In Go there is not such a thing like the Truthiness of a variable.
// Error:
// if price {
//  fmt.Println("We have price!")
// }

// only one if branch will be executed
if price < 100 {
    fmt.Println("It's cheap!")
} else if price == 100 {
    fmt.Println("On the edge")
} else { //executed only once if all the if branches are false (it's optional)
    fmt.Println("It's Expensive!")
}

Simple IF

อธิบายรวดเดียวกันไปเลย ด้วยโค๊ดข้างล่างนี้ ง่ายดี

package main
 
import (
    "fmt"
    "strconv"
)
 
func main() {
 
    // converting string to int:
    i, err := strconv.Atoi("45")
 
    // error handling
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println(i)
 
    }
 
    // simple (short) statement ->  the same effect as the above code
    // i and err are variables scoped to the if statement only
    if i, err := strconv.Atoi("34"); err == nil {
        fmt.Println("No error. i is ", i)
    } else {
        fmt.Println(err)
    }
}

For Loops การวนทำ ตามจำนวนข้อมูล

อธิบายรวดเดียวกันไปเลย ด้วยโค๊ดข้างล่างนี้ ง่ายดี


package main
 
import "fmt"
 
func main() {
 
    // printing numbers from 0 to 9
    for i := 0; i < 10; i++ {
        fmt.Println(i)
    }
 
    // has the same effect as a while loop in other languages
    // there is no while loop in Go
    j := 10
    for j >= 0 {
        fmt.Println(j)
        j--
    }
 
    // handling of multiple variables in a for loop
    for i, j := 0, 100; i < 10; i, j = i+1, j+1 {
        fmt.Printf("i = %v, j = %v\n", i, j)
    }
 
    // infinite loop
    // sum := 0
    // for {
    //  sum++
    // }
    // fmt.Println(sum) //this line is never reached
}

หากต้องการที่จะ break (หยุดการทำงาน) หรือ continue (ต่อเนื่อง จะข้ามรอบการทำงานนั้น) จะทำอย่างไร

 //** CONTINUE STATEMENT **//
 
// It works just the same as in C,  Java or Python.
// The continue statement rejects all the remaining statements in the current iteration of the loop
// and moves the control back to the top of the loop.


// printing even numbers less than or equal to 10
for i := 1; i <= 10; i++ {
    if i%2 != 0 {
        continue    // skipping the remaining code in this iteration
    }
    fmt.Println(i)
}


// **BREAK STATEMENT **//

// It is used to terminate the innermost for or switch statement.
// It works just the same as in C,  Java or Python.

// finding 10 numbers divisible by 13 
count := 0 
for i := 0; true; i++ {
    if i%13 == 0 {
        fmt.Printf("%d is divisible by 13\n", i)
        count++
    }

    if count == 10 { //if 10 numbers were found, break!
        break //it breaks the current loop (inner loop if there are more loops)
    }
}

// the break statement is not terminating the program entirely;
fmt.Println("Just a message after the for loop")

จะลืมได้ไง Switch Statement

package main
 
import "fmt"
 
func main() {
 
    language := "golang"
 
    switch language {
    case "Python": //values must be comparable (compare string to string)
        fmt.Println("You are learning Python! You don't use { } but indentation !! ")
        // an implicit break is added here
    case "Go", "golang": //compare language with "Go" OR "golang"
        fmt.Println("Good, Go for Go!. You are using {}!")
    default:
        // the default clause the equivalent of the else clause of an if statement
        // and gets executed if no testing condition is true.
        fmt.Println("Any other programming language is a good start!")
    }
 
    n := 5
    // comparing the result of an expression which is bool to another bool value
    switch true {
    case n%2 == 0:
        fmt.Println("Even!")
    case n%2 != 0:
        fmt.Println("Odd!")
    default:
        fmt.Println("Never here!")
    }
 
    //** Switch simple statement **//
 
    // Syntax: statement (n:=10), semicolon and a switch condition
    //(true in this case, we are comparing boolean expressions that return true)
    // we can remove the word "true" because it's the default
    switch n := 10; true {
    case n > 0:
        fmt.Println("Positive")
    case n < 0:
        fmt.Println("Negative")
    default:
        fmt.Println("Zero")
    }
}

ใส่ความเห็น

อีเมลของคุณจะไม่แสดงให้คนอื่นเห็น ช่องข้อมูลจำเป็นถูกทำเครื่องหมาย *