Accessing Parent Fields from Embedded Methods in Go: Is it Feasible?
In Go, embedded methods allow embedding types into other types, enabling code reuse and providing a simpler interface. However, a common question arises: can embedded methods access fields of the parent type?
Background:
Go's embedding mechanism leverages composition to extend the functionality of a type without inheritance. When a type is embedded, its fields and methods become part of the embedding type.
Goal:
The aim of this question relates to creating an Active Record style ORM for Go, where methods are embedded on the user struct to abstract away data store operations.
Example:
type Foo struct { *Bar Name string } func (s *Foo) Method() { // How to access "Name" field from this embedded method? }
Question:
Is there a way to make top-level fields (parent fields) accessible from embedded methods like s.Name or call s.Method()?
Answer:
Go does not natively support accessing parent fields from embedded methods. The receiver of the embedded method is strictly bound to the embedded type in this case, *Bar. Therefore, accessing parent fields directly is not possible.
Alternative Approaches:
The above is the detailed content of Can Embedded Methods in Go Access Parent Fields?. For more information, please follow other related articles on the PHP Chinese website!