【问题标题】:Can't access function when passing object and catching it in a interface{}传递对象并在接口中捕获它时无法访问函数{}
【发布时间】:2014-07-10 05:10:55
【问题描述】:

这是我想要做的:

package products

ProductManager struct {
    products []*Product
    index    int64
}

func NewPM() *ProductManager {
    return &ProductManager{}
}

func (p *ProductManager) List() []*Product {
    return p.products
}

---

var productManager = products.NewPM()

func main() {
    api := Api{}
    api.Attach(productManager, "/products")
}

func (api Api) Attach(rm interface{}, route string) {
    // Apply typical REST actions to Mux.
    // ie: Product - to /products
    mux.Get(route, http.HandlerFunc(index(rm)))
}

func index(rm interface{}) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        // allRecords := rm.List() - DOESN'T WORK. No method found.
        result := reflect.TypeOf(rm) // Works, shows me the correct type.
        method := result.Method(0).Name // Works as well! Shows me a function on the type.
        w.Write([]byte(fmt.Sprintf("%v", method)))
    }
}

知道为什么我不能在我的productManager 对象上调用List() 函数吗?我可以看到 Type 的函数,甚至可以在 index() 处理程序中获得正确的 Type 名称。

【问题讨论】:

    标签: function interface go


    【解决方案1】:

    很简单:rm 是一个空的接口变量,所以它没有任何方法,这正是interface{} 的意思:没有方法。如果你知道rm 的动态类型是*ProductManager,你可以键入断言它(但你可以传递*ProductManager)也许你必须在更长的时间内键入rm 上的开关。 (顺便说一句:使用interface{} 几乎总是一个坏主意。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-24
      • 1970-01-01
      • 2011-09-12
      相关资源
      最近更新 更多