[ Golang ] หัดเขียน Golang | Part.4 [ If/Else ]

Siriwat J.
2 min readJan 27, 2021

--

สวัสดีครับทุกคนน เรามา Note Golang 💕 กันต่ออ สำหรับ Part .3 เรื่อง control flow (for loop ) ลิ้งค์ตามด้านล่างเลยย 👇

[ Golang ] หัดเขียน Golang | Part.3 | by Siriwat J. | Jan, 2021 | Medium

Control Flow (ต่อ)

If

ในภาษา Go เงื่อนไข if จะไม่ต้องใส่ ( ) ก็ได้ หน้าตาของ if จะเป็นแบบนี้

if condition {
//body
}

condition คือเงื่อนไข หากเป็น true ถึงจะทำงานใน body

เช่น

x := 3
if x>1 {
fmt.Println("Hello World")
}

Output

Hello World

อธิบาย

จะเห็นว่า x = 3 และ condition ของเราคือ x > 1 ซึ่งเป็นจริง ทำให้แสดงข้อความ Hello World

If แบบแปลกๆใน Go

ในภาษา Go เราสามารถประกาศตัวแปรแบบสั้น(init) ก่อนเงื่อนไข( Condition )ได้

if init ; condition {
//body
}

ตัวอย่างเช่น

if x:=3 ; x>1{
fmt.Println("Hello World")
}

Output

Hello World

อธิบาย

Code จะทำงานเหมือนด้านบน แต่ต่างกันที่ ตัวแปร x จะสามารถใช้งานได้เพียงใน scope ของ if เท่านั้น

‘งงมั้ยนะ’

ถ้าเราเปรียบเทียบกับ code ด้านบน

x := 3
if x>1{
fmt.Println("Hello")
}
fmt.Println(x)
//Output
Hello
3

และ

if x:=3 ; x>1{
fmt.Println("Hello World")
}
fmt.Println(x)
//Output
undefined : x

จะเห็นว่า เมื่อเราแสดงค่า x นอก scope ของ if แล้ว x ของเราจะเป็น undefined

else if & else

หากเราต้องการเพิ่มเงื่อนไขในการ Check เราสามารถเขียนได้ดังนี้

if condition1 {
//body1
} else if condition2 {
//body2
} else if condition3{
//body3
} else{
//body
}

ตัวอย่าง control flow ของ else f

https://qph.fs.quoracdn.net/main-qimg-f9ea2d61b489912404f67aafad6c03c3

กล่าวคือ ถ้าตรวจสอบเงื่อนไขแรกไม่ผ่าน ก็จะเช็คเงื่อนไขต่อไปเรื่อยๆ จนกว่าจะเป็นจริง.. และถ้าไม่เข้าเงื่อนไขใดๆ ก็จะเข้าไปทำงานใน body ของ else

ตัวอย่างเช่น

x := 3
if x < 1 {
fmt.Println("A")
} else if x > 2 {
fmt.Println("B")
}else{
fmt.Println("C")
}

Output

B

อีกสักตัวอย่าง

x := 3
if x < 1 {
fmt.Println("A")
} else if x < 2 {
fmt.Println("B")
}else{
fmt.Println("C")
}

Output

C

ไว้เจอกันใน Part ต่อไปนะครับบ 😁😀🎈🎈

--

--

No responses yet