Home > Backend Development > Golang > Can Embedded Methods in Go Access Parent Object Fields?

Can Embedded Methods in Go Access Parent Object Fields?

Barbara Streisand
Release: 2024-12-06 18:36:21
Original
917 people have browsed it

Can Embedded Methods in Go Access Parent Object Fields?

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()
}
Copy after login

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:

  • Adding an interface{} field to the embedded type and setting it to the containing type during initialization.
  • Adopting the approach of db.Save(user) rather than user.Save(), which provides better extensibility and reduces the risk of global state issues.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template