简体   繁体   中英

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?

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM