这是我正在尝试做的事情:
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()
函数吗?我可以看到类型的功能,甚至可以在 index()
处理程序中获得正确的类型名称。
最佳答案
非常简单:rm
是一个空接口(interface)变量,因此它没有任何方法,这正是 interface{}
的意思:没有方法。如果您知道 rm
的动态类型是 *ProductManager
,您可以键入断言它(但是您可以传递一个 *ProductManager
)也许您从长远来看,必须在 rm
上键入 switch。 (顺便说一句:使用 interface{}
几乎总是一个坏主意。)
关于function - 传递对象并将其捕获在接口(interface)中时无法访问函数{},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23785225/