Struct และ Interface ต่างกันอย่างไรใน Go

Sharing is caring!

Struct ใน Go คืออะไร?

Struct คือโครงสร้างข้อมูลชนิดหนึ่งในภาษา Go ซึ่งทำหน้าที่เก็บ field หลาย ๆ ตัวรวมกัน เพื่อแทนวัตถุหรือ entity เช่น ผู้ใช้, สินค้า, รถ ฯลฯ

โครงสร้างตัวอย่าง struct:

type Person struct {
    Name string
    Age  int
}
  

สามารถใช้งานได้ดังนี้:

p := Person{Name: "King", Age: 34}
fmt.Println(p.Name) // "King"
  

Interface ใน Go คืออะไร?

Interface ในภาษา Go คือชุดของ method signature ที่ struct ใด ๆ ก็สามารถ implement ได้โดยไม่ต้อง explicit declare เหมือนภาษาอื่น

ตัวอย่าง Interface:

type Speaker interface {
    Speak() string
}
  

Struct ที่ implement interface:

type Dog struct {}

func (d Dog) Speak() string {
    return "Woof!"
}
  

ใช้งานร่วมกัน:

func SaySomething(s Speaker) {
    fmt.Println(s.Speak())
}

func main() {
    SaySomething(Dog{}) // พิมพ์ "Woof!"
}
  

ความแตกต่างระหว่าง Struct และ Interface

หัวข้อStructInterface
การใช้งานเก็บข้อมูลกำหนดพฤติกรรม (methods)
สามารถมี method ได้หรือไม่ได้ (ผ่าน receiver)เฉพาะ signature เท่านั้น
ใช้กับ Polymorphismไม่ได้ได้
การ implementautomatic implicit implement

ภาพประกอบ: เปรียบเทียบ Struct และ Interface

การใช้งานร่วมกัน

คุณสามารถใช้ struct กับ interface เพื่อเขียนโปรแกรมแบบยืดหยุ่นได้ เช่น ใช้ interface เป็น parameter เพื่อรับ struct ได้หลายแบบ:

type Logger interface {
    Log(msg string)
}

type ConsoleLogger struct{}

func (c ConsoleLogger) Log(msg string) {
    fmt.Println(msg)
}

func Process(l Logger) {
    l.Log("เริ่มประมวลผล...")
}
  

หาก struct ใหม่ตรงกับ interface ก็สามารถใช้งานได้ทันที!

Best Practices

  • ใช้ struct สำหรับเก็บข้อมูล
  • ใช้ interface เพื่อออกแบบให้รองรับหลายพฤติกรรม
  • กำหนด interface ที่จำเป็น ไม่ควรใหญ่เกินไป (ใช้ principle: Interface Segregation)
  • ตั้งชื่อ interface ให้ลงท้ายด้วย -er เช่น: Reader, Writer

บทสรุป

Struct และ Interface เป็น 2 สิ่งสำคัญในภาษา Go ที่ใช้ร่วมกันอย่างทรงพลัง Struct ช่วยเก็บข้อมูลแบบมีโครงสร้าง ส่วน Interface ทำให้ระบบยืดหยุ่นและรองรับ Polymorphism ได้อย่างสะอาด


บทความโดย: poolsawat.com | เขียนโดย: King Pool

Leave a Reply

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