All Articles
OOP ในภาษา Go

2023-01-20

OOP ในภาษา Go

Read on Medium

แชร์บทความนี้

OOP ในภาษา Go

ถ้ามาจาก Java หรือ C++ แล้วเปิด Go ครั้งแรก เราอาจมองหา class, extends และ implements เหมือนเข้าครัวใหม่แล้วหาชุดมีดเล่มเดิม แต่ Go จงใจจัดครัวต่างออกไปครับ มันมี Struct, Method, Interface และ Composition ให้ใช้ โดยไม่สร้างระบบ Class hierarchy แบบดั้งเดิม

ดังนั้นคำถามที่แม่นกว่าคือไม่ใช่ “Go เป็น OOP ไหม” แต่เป็น “เราจะใช้แนวคิดเรื่องข้อมูล พฤติกรรม การซ่อนรายละเอียด และ Polymorphism ในสไตล์ Go อย่างไร”

Struct เก็บสถานะ Method บอกพฤติกรรม

สร้าง Person ด้วย Struct:

type Person struct {
	Name string
	Age  int
}

ผูก Method ด้วย Receiver:

func (p Person) Greet() string {
	return fmt.Sprintf("สวัสดีครับ ผมชื่อ %s", p.Name)
}

เรียกใช้งาน:

person := Person{Name: "Nan", Age: 30}
fmt.Println(person.Greet())

Receiver p Person ทำให้ Greet เป็น Method ของ Person แต่ Struct ไม่ใช่ Class และ Receiver ไม่ใช่ this แบบเดียวกันทุกมุม เราเลือกได้ว่าจะรับเป็น Value หรือ Pointer

Value receiver กับ Pointer receiver

Value receiver ได้สำเนาของค่า:

func (p Person) Greet() string {
	return "สวัสดี " + p.Name
}

Pointer receiver ใช้แก้สถานะของค่าต้นฉบับและหลีกเลี่ยงการ Copy Struct ขนาดใหญ่:

func (p *Person) Birthday() {
	p.Age++
}
person := Person{Name: "Nan", Age: 30}
person.Birthday()
fmt.Println(person.Age) // 31

หลักใช้ง่าย ๆ:

  • Method ต้องแก้ Field ให้ใช้ Pointer receiver
  • Struct ใหญ่หรือมี Resource ภายใน มักใช้ Pointer receiver
  • Struct เล็กและเป็น Value-like เช่น Coordinate อาจใช้ Value receiver
  • พยายามใช้รูปแบบสม่ำเสมอใน Type เดียวกัน

Pointer ไม่ได้แปลว่าเร็วกว่าทุกกรณี และ Value ก็ไม่ได้แปลว่าปลอดภัยเสมอ ดู Semantics ก่อน Benchmark ครับ

Encapsulation ใช้ตัวพิมพ์ใหญ่และขอบเขต Package

Go ไม่มี Keyword private แต่ใช้ชื่อกำหนดการ Export:

  • ขึ้นต้นตัวพิมพ์ใหญ่ มองเห็นจาก Package อื่น
  • ขึ้นต้นตัวพิมพ์เล็ก ใช้ได้ภายใน Package
type BankAccount struct {
	owner   string
	balance int64
}

func NewBankAccount(owner string) *BankAccount {
	return &BankAccount{owner: owner}
}

func (a *BankAccount) Deposit(amount int64) error {
	if amount <= 0 {
		return errors.New("amount must be positive")
	}

	a.balance += amount
	return nil
}

func (a BankAccount) Balance() int64 {
	return a.balance
}

ผู้ใช้ Package เปลี่ยน balance ตรง ๆ ไม่ได้ ต้องผ่าน Method ที่รักษากฎของระบบ นี่คือ Encapsulation แบบ Go: ซ่อนรายละเอียดไว้หลังขอบเขต Package และเปิด API เท่าที่จำเป็น

อย่ารีบสร้าง Getter/Setter ให้ทุก Field แบบเครื่องจักร ถ้า Field เปิดให้อ่านและเขียนได้อย่างปลอดภัย Export ตรง ๆ ก็เป็นสไตล์ Go ที่ปกติ แต่ถ้ามี Invariant เช่นยอดเงินห้ามติดลบ ควรซ่อนและให้ Method ควบคุมครับ

Composition แทน Inheritance

Go ไม่มี Employee extends Person แต่ Embed Type เพื่อประกอบความสามารถได้:

type Employee struct {
	Person
	EmployeeID string
}
employee := Employee{
	Person: Person{Name: "Nan", Age: 30},
	EmployeeID: "EMP-001",
}

fmt.Println(employee.Name)
fmt.Println(employee.Greet())

Field และ Method ของ Person ถูก Promote ให้เรียกผ่าน Employee ได้สะดวก แต่ Embedding ไม่ใช่ Inheritance Employee ไม่ได้กลายเป็น Subclass ของ Person และไม่ควรอธิบายว่า “Employee is-a Person” ในความหมายเดียวกับ Class hierarchy

มันใกล้กับการประกอบ Lego: เราเอาชิ้นที่มีความสามารถอยู่แล้วมาต่อเป็นของใหม่ โดยยังมองเห็นว่าชิ้นไหนมาจากไหน

Interface เป็นสัญญาที่ไม่ต้องประกาศ implements

type Speaker interface {
	Speak() string
}

type Dog struct {
	Name string
}

func (d Dog) Speak() string {
	return d.Name + " says woof"
}

type Robot struct {
	Model string
}

func (r Robot) Speak() string {
	return r.Model + " says beep"
}

ทั้ง Dog และ Robot ใช้เป็น Speaker ได้ทันที เพราะมี Method set ตรงกับ Interface:

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

Announce(Dog{Name: "Milo"})
Announce(Robot{Model: "R2"})

นี่คือ Structural typing และ Polymorphism แบบ Go Type ไม่ต้องรู้ล่วงหน้าว่ามี Interface อยู่ จึงลดการผูกกันระหว่าง Package

แนวปฏิบัติที่ดีคือ “รับ Interface คืน Concrete type” และให้ฝั่งผู้ใช้ประกาศ Interface เล็ก ๆ ตามสิ่งที่ต้องการ ไม่จำเป็นต้องสร้าง Interface ใหญ่ครอบทุก Method ของ Service เหมือนทำปลั๊กไฟ 30 รูเพราะกลัววันหนึ่งอาจต้องเสียบเพิ่มครับ

ตรวจ Interface ตอน Compile ได้

ถ้าอยากยืนยันว่า Type ทำตาม Contract:

var _ Speaker = (*Robot)(nil)

ถ้า *Robot ไม่มี Speak() ตามที่กำหนด โค้ดจะ Compile ไม่ผ่าน เทคนิคนี้เหมาะเมื่อความสัมพันธ์ไม่ชัดจากจุดใช้งาน แต่ไม่จำเป็นต้องใส่ทุก Type จนไฟล์เต็มไปด้วยใบรับรองครับ

Polymorphism โดยไม่ต้องมี Base class

type Shape interface {
	Area() float64
}

type Rectangle struct {
	Width  float64
	Height float64
}

func (r Rectangle) Area() float64 {
	return r.Width * r.Height
}

type Circle struct {
	Radius float64
}

func (c Circle) Area() float64 {
	return math.Pi * c.Radius * c.Radius
}

func TotalArea(shapes []Shape) float64 {
	var total float64
	for _, shape := range shapes {
		total += shape.Area()
	}
	return total
}

TotalArea ไม่สนว่าวัตถุเป็น Rectangle หรือ Circle ขอเพียงคำนวณ Area ได้ก็พอ นี่ทำให้เราเพิ่ม Shape ใหม่โดยไม่ต้องแก้ Function เดิม

Nil Interface กับกับดักที่ดูเหมือนไม่มีอะไร

Interface เก็บทั้ง Dynamic type และ Dynamic value จึงเกิดกรณีนี้ได้:

var robot *Robot = nil
var speaker Speaker = robot

fmt.Println(speaker == nil) // false

speaker ไม่เป็น nil เพราะยังเก็บ Type ว่าเป็น *Robot แม้ Value ข้างในเป็น nil ถ้า Method ไป Dereference Receiver อาจ Panic ได้ วิธีป้องกันคือหลีกเลี่ยงคืน Typed nil ในรูป Interface และเขียน Test ให้กรณีไม่มีค่าชัดเจน

Go ไม่ได้เร็วเพราะไม่มี Class เพียงอย่างเดียว

การบอกว่า Go Performance ดีกว่าภาษาอื่นเพราะไม่มี Class เป็นข้อสรุปที่แรงเกินไป ประสิทธิภาพขึ้นกับ Compiler, Runtime, Allocation, Algorithm, I/O และ Workload อีกมากมาย

เหตุผลที่ Go เลือก Struct, Interface และ Composition คือทำให้โมเดลภาษากระชับและส่งเสริมการประกอบส่วนเล็ก ๆ ไม่ใช่ใบรับรองว่าโค้ดทุกชิ้นจะเร็วโดยอัตโนมัติ ถ้าต้องการรู้ว่าเร็วไหม ให้ Benchmark และ Profile ครับ อย่าให้ความเชื่อถือ Stopwatch แทนเรา

สรุป

Go ไม่มี Class hierarchy แต่เรายังสร้างระบบที่มีข้อมูล พฤติกรรม Encapsulation และ Polymorphism ได้ครบ:

  • Struct เก็บข้อมูล
  • Method ผูกพฤติกรรมกับ Type
  • Package boundary ช่วยซ่อนรายละเอียด
  • Embedding และ Composition นำความสามารถมาประกอบกัน
  • Interface สร้างสัญญาแบบ Implicit

หัวใจของ OOP ใน Go ไม่ใช่พยายามสร้าง Java ขึ้นมาใหม่ด้วย Struct แต่คือออกแบบ Type เล็ก ๆ Interface แคบ ๆ และประกอบสิ่งเหล่านั้นตามพฤติกรรมที่ระบบต้องการ ถ้า Class hierarchy เปรียบเหมือนต้นไม้ใหญ่ Go จะชอบกล่อง Lego มากกว่า—ชิ้นไม่เยอะ แต่ต่อเป็นของใหม่ได้โดยไม่ต้องย้ายรากทั้งต้นครับ

อ่านต่อจากเอกสารทางการ: A Tour of Go และ Effective Go

© 2026 Nanpipat Klinpratoom. All Rights Reserved.