Dynamically call method on interface{} regardless of receiver type

前端 未结 3 1716
眼角桃花
眼角桃花 2020-12-13 03:03

I\'m working on a templating system written in Go, which means it requires liberal use of the reflect package. In this specific circumstance I need to be able t

3条回答
  •  失恋的感觉
    2020-12-13 03:41

    This is a good example of golang to implement similar functionality:

    package main
    
    import "fmt"
    
    type Parent struct {
        Attr1 string
    }
    
    type Parenter interface {
        GetParent() Parent
    }
    
    type Child struct {
        Parent //embed
        Attr   string
    }
    
    func (c Child) GetParent() Parent {
        return c.Parent
    }
    
    func setf(p Parenter) {
        fmt.Println(p)
    }
    
    func main() {
        var ch Child
        ch.Attr = "1"
        ch.Attr1 = "2"
    
        setf(ch)
    }
    

    code from : https://groups.google.com/d/msg/golang-nuts/8lK0WsGqQ-0/HJgsYW_HCDoJ

提交回复
热议问题