Struct และ Interface
Go Struct Embedding and Composition
Go has no inheritance. Reuse fields and methods by embedding one struct in another.
สิ่งที่คุณจะได้เรียนรู้
- Embedding a struct
- Promoted fields and methods
- Composition
type Dog struct
DogAnimalName, Describe()Breed
Build types from smaller types
Go has no inheritance. Instead, a struct can embed another struct, and the fields and methods of the embedded type become available on the outer one. This is called composition.
Dog embeds Animal, so dog.Name and dog.Describe() work as if they were declared on Dog. The embedded value can still be reached by its type name, as in dog.Animal.Name. Service gets a Log method by embedding Logger.
ประเด็นสำคัญ
- Dog embeds Animal and gets Name and Describe.
- The embedded value is still reachable:
dog.Animal. - Embedding is composition, not inheritance.
ตัวอย่าง Go ที่รันได้
main.go
package main
import "fmt"
type Animal struct {
Name string
}
func (a Animal) Describe() string {
return a.Name + " is an animal"
}
type Dog struct {
Animal // embedded: Dog gets Name and Describe
Breed string
}
func (d Dog) Speak() string {
return d.Name + " says woof"
}
type Logger struct{ Prefix string }
func (l Logger) Log(message string) { fmt.Println(l.Prefix + message) }
type Service struct {
Logger
Name string
}
func main() {
dog := Dog{Animal: Animal{Name: "Rex"}, Breed: "Collie"}
fmt.Println(dog.Describe())
fmt.Println(dog.Speak())
fmt.Println(dog.Animal.Name, dog.Breed)
service := Service{Logger: Logger{Prefix: "[api] "}, Name: "users"}
service.Log("started " + service.Name)
}
Rex is an animal
Rex says woof
Rex Collie
[api] started usersฝึกฝน
เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์
เรียนบทนี้จบแล้วใช่ไหม
ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า
ความคืบหน้าของคุณถูกบันทึกไว้ในเบราว์เซอร์นี้ เข้าสู่ระบบเพื่อเก็บไว้ใช้ได้ทุกอุปกรณ์
ฝึกด้วยโจทย์
ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI
- Decorator ของราคา ห่อราคาพื้นฐานด้วยตัวตกแต่ง discount, tax, shipping และ coupon ที่นำไปใช้ตามลำดับ ง่าย
- ขนาดโฟลเดอร์ด้วย Composite คำนวณขนาดรวมของทุกโฟลเดอร์ในต้นไม้ที่โฟลเดอร์ประกอบด้วยไฟล์และโฟลเดอร์อื่น ๆ ปานกลาง