Accessing Parent Fields from Embedded Methods
Background
When embedded methods are used to simplify object-oriented programming, a question arises: can these methods access the fields of the parent object?
Goal
The goal is to create an ORM for Go that mimics the Active Record pattern, where methods like Save() and Delete() are attached to the object being saved or deleted. This approach simplifies code readability and decouples it from the underlying data store.
Example
The code below demonstrates an embedded method (Test()) in the Foo type:
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
Can the embedded method (Test()) access the Name field of the parent (Foo) object?
Answer
No, there is no direct way in Go for an embedded method to access the fields of its parent object. The receiver type of the Test() method is *Bar, while the target object is of type Foo.
Alternative Approaches
If accessing parent fields is essential, possible solutions include:
The above is the detailed content of Can Embedded Methods in Go Access Parent Object Fields?. For more information, please follow other related articles on the PHP Chinese website!