jeudi 19 juillet 2018

Using reflect, how to create struct "type" dynamically?

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?





Aucun commentaire:

Enregistrer un commentaire