วิธีการใช้ รูปแบบชุดคำสั่งภาษา go

ตอบกระทู้

รูปแสดงอารมณ์
:icon_plusone: :like: :plusone: :gfb: :-D :) :( :-o 8O :? 8) :lol: :x :P :oops: :cry: :evil: :twisted: :roll: :wink: :!: :?: :idea: :arrow: :| :mrgreen: :angry: :baa: :biggrin:
รูปแสดงอารมณ์อื่นๆ

BBCode เปิด
[img] เปิด
[url] เปิด
[Smile icon] เปิด

กระทู้แนะนำ
   

มุมมองที่ขยายได้ กระทู้แนะนำ: วิธีการใช้ รูปแบบชุดคำสั่งภาษา go

วิธีการใช้ รูปแบบชุดคำสั่งภาษา go

โดย nuattawoot » 10/11/2017 1:12 pm

วิธีการใช้ รูปแบบชุดคำสั่งภาษา go
จากบทเรียนก่อนหน้านี้ของการเขียนภาษา 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")
    }
}
เป็นการตรวจสอบว่า 9 หาร 2 ได้ซึ่งได้เศษ 0 เช็คว่าถ้าผลลัพธ์เป็น 0 ก็เป็นเลขคี่ หรือ 4 หาร 4 ได้เศษเป็น 0 นั่นเป็นแปลว่า 4 หารด้วย 4 ลงตัวเป็นต้น

การใช้งาน 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)
}

ข้างบน