Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära Struct Embedding for Reuse | Section
Struct-Oriented Design in Go

bookStruct Embedding for Reuse

Svep för att visa menyn

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

main.go

copy
123456789101112131415161718192021222324252627
package 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.

question mark

What is a key effect of method promotion when you embed one struct inside another in Go?

Select the correct answer

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 1. Kapitel 10

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

Avsnitt 1. Kapitel 10
some-alt