Struct Embedding for Reuse
Swipe to show menu
Struct embedding in Go provides a powerful way to achieve code reuse and extension without relying on inheritance. Instead of subclassing, you can embed one struct inside another, allowing the outer struct to access the fields and methods of the embedded type directly. This approach fits naturally with Go's emphasis on composition over inheritance, making your code more flexible and idiomatic.
To embed a struct, you simply declare it as a field in another struct, omitting the field name. This syntax not only includes the embedded struct's fields and methods in the outer struct's method set, but also enables what is known as method promotion. When you embed a struct, its exported methods become accessible as if they were defined on the embedding struct itself, unless you explicitly override them.
main.go
123456789101112131415161718192021222324252627package main import ( "fmt" ) // BaseRepository provides common database operations. type BaseRepository struct { tableName string } func (b *BaseRepository) FindAll() string { return "Fetching all records from " + b.tableName } // UserRepository embeds BaseRepository to reuse its methods. type UserRepository struct { BaseRepository } func main() { userRepo := UserRepository{ BaseRepository: BaseRepository{tableName: "users"}, } // Method FindAll is promoted from BaseRepository to UserRepository. fmt.Println(userRepo.FindAll()) }
In the code above, you see that UserRepository embeds BaseRepository. The FindAll method, which is defined on BaseRepository, is promoted to UserRepositoryโyou can call userRepo.FindAll() directly, even though UserRepository does not define this method itself. This is method promotion in action.
However, if UserRepository defines its own FindAll method, it will shadow the one from BaseRepository. This is called field or method shadowing: the outer struct's implementation takes precedence, and the embedded method is no longer directly accessible through the outer struct. You can still access the original by qualifying it with the embedded type's name, such as userRepo.BaseRepository.FindAll(). This mechanism allows you to extend or override behavior as needed while still reusing code from embedded structs.
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat