Background:
After extensive research and testing, the author believes that embedded methods in Go cannot access "parent" fields. This question explores whether there are any known exceptions or alternative approaches.
Goal:
The objective is to create an Active Record style ORM for Go, where CRUD operations would be embedded in the user struct. This would provide increased readability and abstraction from the back end data store.
Example:
The provided Go code snippet attempts to access the "Name" field of the "Foo" struct from the "Test" method of the embedded "Bar" struct. However, this results in a compilation error.
Question:
Is there any mechanism in Go that allows embedded methods to access fields of the enclosing struct?
Answer:
Go does not support direct access to parent fields within embedded methods. The receiver type of the "Test" method is a "Bar" pointer, and there is no way for the method to determine whether this pointer is embedded or stands alone.
Possible Solutions:
One workaround involves adding an interface{} member to the "Bar" struct and requiring that the containing type be assigned to this member. However, this is not an elegant solution and introduces additional complexity.
Alternative Approach:
Instead of embedding methods, the author suggests using a different API structure, such as "db.Save(user)" rather than "user.Save()". This approach allows for easier extension to multiple databases and reduces reliance on global state.
The above is the detailed content of Can Embedded Go Methods Access Enclosing Struct Fields?. For more information, please follow other related articles on the PHP Chinese website!