0

Consider the following struct :

type Foo struct{}

func (f *Foo) foo() {
    fmt.Println("Hello")
}

Using reflect I would like to generate a custom struct type that overrides a set of methods. When doing the work manually what I want to do is :

type Edit struct{
    Foo
}

func (e *Edit) foo() {
    e.Foo.foo()
    fmt.Println("World")
}

But instead of writing this manually, I would like to make a function that does such override automatically for any given struct.


I know that I can instantiate a struct using :

res := reflect.New(reflect.TypeOf(origin))

but in this situation, we can't edit methods.

So how with reflect can I create a struct type that wraps an existing type like explained above?

Rémi Rousselet
  • 256,336
  • 79
  • 519
  • 432

1 Answers1

0

You can achieve something extremely similar to what you are asking for using Method Values. You could do something like the following:

package main

import (
    "fmt"
)

type Foo struct {
    sayHelloAgain func()
}

func (f *Foo) SayHello() { 
    fmt.Print("Hello,")
    f.sayHelloAgain() 
}

func main() {
    edit := struct{Foo}{}
    edit.sayHelloAgain = func(){ fmt.Println(" World!") }
    edit.SayHello()

}

Go Playground

As you can see, you can create an anonymous struct which will be able to call the SayHello function, which then calls the receiver's dynamically set sayHelloAgain method.

I think this will be the closest you will get to your goal, and works as you requested (without relection)

Geoherna
  • 3,523
  • 1
  • 24
  • 39