จากบทเรียนก่อนหน้านี้ของการเขียนภาษา Go หรือ Go Lang ภาษาใหม่ของ Google เราจะมาศึกษาต่อเนื่องเกี่ยวกับ Decistion Making หรือ if then else
โค้ด: เลือกทั้งหมด
package main
import "fmt"
number=9
func main() {
if number%2 == 0 {
fmt.Println("even")
} else {
fmt.Println("odd")
}
if number%4 == 0 {
fmt.Println("divisible by")
}
}
การใช้งาน Switch Case มีรูปแบบดังนี้
โปรแกรมคำนวนเกรด
โค้ด: เลือกทั้งหมด
import "fmt"
func main() {
var grade string = "B"
var marks int = 90
switch marks {
case 90: grade = "A"
case 80: grade = "B"
case 50,60,70 : grade = "C"
default: grade = "D"
}
switch {
case grade == "A" :
fmt.Printf("Excellent!\n" )
case grade == "B", grade == "C" :
fmt.Printf("Well done\n" )
case grade == "D" :
fmt.Printf("You passed\n" )
case grade == "F":
fmt.Printf("Better try again\n" )
default:
fmt.Printf("Invalid grade\n" );
}
fmt.Printf("Your grade is %s\n", grade );
}
Select Statement
โค้ด: เลือกทั้งหมด
package main
import "fmt"
func fibonacci(c, quit chan int) {
x, y := 0, 1
for {
select {
case c <- x:
x, y = y, x+y
case <-quit:
fmt.Println("quit")
return
}
}
}
func main() {
c := make(chan int)
quit := make(chan int)
go func() {
for i := 0; i < 10; i++ {
fmt.Println(<-c)
}
quit <- 0
}()
fibonacci(c, quit)
}