Struct và interface

Go Struct Embedding and Composition

Go has no inheritance. Reuse fields and methods by embedding one struct in another.

  • Trung cấp
  • Đọc trong 4 phút
  • 1 ví dụ chạy được
Bạn sẽ học được gì
  • Embedding a struct
  • Promoted fields and methods
  • Composition
type Dog struct
  • Dog
    • AnimalName, 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.

Những điểm quan trọng

  1. Dog embeds Animal and gets Name and Describe.
  2. The embedded value is still reachable: dog.Animal.
  3. Embedding is composition, not inheritance.

Ví dụ Go chạy được

Go
Chạy code →
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)
}
Lấy nút Run cho ví dụ này Kết quả khi chạy
Rex is an animal
Rex says woof
Rex Collie
[api] started users

Luyện tập

Mở ví dụ trong trình biên dịch online, đổi một giá trị hoặc thêm một dòng, rồi đoán kết quả trước khi chạy. Sau đó cố ý làm code bị lỗi và đọc thông báo của trình biên dịch.

Bạn học xong bài này chưa?

Đánh dấu đã học để theo dõi tiến độ của bạn.

Tiếp theo: Temperature Converter →

Luyện tập với thử thách

Áp dụng kiến thức của bài học này để giải một bài toán thực tế. Mỗi thử thách chạy ngay trên trình duyệt, có kiểm thử tức thì và AI nhận xét.

Tất cả thử thách