douzi7219 2018-07-19 16:31
浏览 42

使用反射,如何动态创建结构“类型”?

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?

  • 写回答

1条回答 默认 最新

  • dsxrq28228 2018-07-19 17:43
    关注

    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)

    评论

报告相同问题?