- Go KHÔNG có class.
- Struct là kiểu dữ liệu composite, methods gắn vào struct qua receiver.
- Composition thay vì inheritance: embed struct trong struct khác.
go
// Định nghĩa struct
type User struct {
Name string
Age int
}
// Method gắn vào struct qua value receiver
func (u User) Hello() string {
return "Hello, " + u.Name
}
// Pointer receiver để modify struct
func (u *User) SetName(name string) {
u.Name = name
}
// Khởi tạo struct
u := User{Name: "Alice", Age: 30}
fmt.Println(u.Hello()) // "Hello, Alice"
// Composition thay inheritance
type Admin struct {
User // embed User
Level int
}
admin := Admin{User: User{Name: "Bob"}, Level: 1}
fmt.Println(admin.Hello()) // kế thừa method của User