Can Embedded Methods Access Parent Fields?
In Go, embedded methods are a powerful mechanism for code reuse and organization. However, a common question arises: can embedded methods directly access the fields of their parent struct?
Background
For context, suppose you're creating an Active Record-style ORM for Go where common CRUD methods are embedded in the user struct for readability and abstraction. This would allow you to write user.Save() instead of data.Save(user).
Example
Consider this code snippet:
package main import ( "fmt" "reflect" ) func main() { test := Foo{Bar: &Bar{}, Name: "name"} test.Test() } type Foo struct { *Bar Name string } func (s *Foo) Method() { fmt.Println("Foo.Method()") } type Bar struct { } func (s *Bar) Test() { t := reflect.TypeOf(s) v := reflect.ValueOf(s) fmt.Printf("model: %+v %+v %+v\n", s, t, v) fmt.Println(s.Name) s.Method() }
Question Revisited
The question at hand is whether there's a way to make top-level fields accessible from embedded methods. In the example above, the Test method is embedded in Bar and attempts to access the Name field from the parent Foo struct.
Answer
Unfortunately, Go does not provide any direct mechanism for embedded methods to access the fields of their parent struct. The receiver of the Test method is a pointer to Bar, and there is no way for Go to determine if it is embedded or not.
Possible Solution
To achieve this functionality, one potential workaround is to add an interface{} member to the Bar struct, requiring that types that implement it set the member to the containing type. The initialization of this member could either be the responsibility of the caller or handled through an ORM method. However, this approach introduces additional complexity and potential maintenance issues.
Alternative Perspective
Alternatively, consider the possibility that structuring the API as db.Save(user) may not be as detrimental as it seems. This approach offers a straightforward way to support multiple databases and avoids relying on global state.
The above is the detailed content of Can Embedded Go Methods Access Parent Struct Fields?. For more information, please follow other related articles on the PHP Chinese website!